C Kata - Double Char

By Lochard | As a newbie programmer | 2 Oct 2022


Learning from YayoDrayber, I am sharing my CodeWars Kata.

 

DESCRIPTION:

Given a string, you have to return a string in which each character (case-sensitive) is repeated once.

 

Examples (Input -> Output):

* "String" -> "SSttrriinngg"

* "Hello World" -> "HHeelllloo WWoorrlldd"

* "1234!_ " -> "11223344!!__ "

 

Starting code
char *double_char (const char *string, char *doubled)
{
  *doubled = '\0'; // write to doubled

  return doubled; // return it
}
My attempt
char *double_char (const char *string, char *doubled)
{
  char *writing_head = doubled;
  char *reading_head = string - 1;
  while (*++reading_head) {
    *writing_head++ = *reading_head;
    *writing_head++ = *reading_head;
  }
  *writing_head = '\0';

  return doubled; // return it
}
Best Practice and Clever
char *double_char (const char *string, char *doubled)
{
  int k=0,i=0;
  while (string[i]!='\0'){
    doubled[k++]=string[i];
    doubled[k++]=string[i++];
  }
  doubled[k]='\0';
  return doubled;
}

Using index like we would in other languages is a clear way to do it.

 

My Pick
char *double_char (const char *string, char *doubled) {
  char *result = doubled;
  while(*string){
    *doubled++ = *string;
    *doubled++ = *string++;
  }
  *doubled = '\0'; // write to doubled
  return result; // return it
}

So, you can use the input string pointer.

 

My post-Kata snippet
char *double_char (const char *string, char *doubled)
{
  char *d = doubled;
  while (*string) {
    *d++ = *string;
    *d++ = *string++;
  }
  *d = '\0';

  return doubled; // return it
}

My code snippets on GitHub

How do you rate this article?

2


Lochard
Lochard

20240228 Arrived in the UK for about 2 week. All my fears persist. Some are even getting worse. https://github.com/locharp/asylum_diary/


As a newbie programmer
As a newbie programmer

Sharing entry level codes. My snippets on GitHub https://github.com/locharp/code-snippets

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.