C Kata - Double Char

in Programming & Dev2 years ago

Learning from YayoDrayber from Publish, 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

Sort:  

Congratulations @lochard! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You published more than 10 posts.
Your next target is to reach 20 posts.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out the last post from @hivebuzz:

Our Hive Power Delegations to the September PUM Winners
Feedback from the October 1st Hive Power Up Day
Hive Power Up Month Challenge 2022-09 - Winners List