-2

I need to write a function which will take a string as input and outputs as below

input : aaabbdd output : a3b2d2 input : aaaaaaaaaaaaaaaabbccc output : a16b2c3 

basically I have to append the count to every character. I should not use itoa() to convert int to string

I wrote the logic. But I got struck at appending the number to the string. For example, if count is 16, how can I add the number 16 to end of a string?

My logic is as given below.

#include <stdio.h> void str1(char *str) { int i, j, cnt; int len = strlen(str); char *nstr = (char *) malloc(len * sizeof(char)); int k = 0; cnt = 1; for(i = 0, j = 1; i < len - 1;) { if(str[i] == str[j]) { j++; cnt++; continue; } else { if(cnt == 1) { nstr[k++] = str[i]; } else { nstr[k++] = str[i]; nstr[k++] = cnt; // GOT STUCK HERE } i = j; j = i + 1; cnt = 1; } } printf("\n%s\n", nstr); } main() { char str[] = "aaaaaaaaaaaaaaaabbcdd"; str1(str); } 
9
  • 6
    show some code, what you got, what won't work. Commented Sep 8, 2014 at 18:21
  • possible duplicate of c string and int concatenation Commented Sep 8, 2014 at 18:21
  • please post what you have done so far Commented Sep 8, 2014 at 18:22
  • why do you want to store it, you are only asked to output it? Commented Sep 8, 2014 at 18:37
  • @Pieter21 : How can I output it? Are you suggesting that just print character and number instead of storing it in a buffer and printing entire string at once? Commented Sep 8, 2014 at 18:40

2 Answers 2

1

You can implement itoa yourself. The logic is as follows:

  • If the number is zero, append zero (in your case, this should never happen, but in general case this is obviously possible)
  • Prepare a temporary buffer for your output. The size depends on the number of bits in the integer that you are printing
  • Store the last digit by computing n % 10
  • Divide the number by ten using integer division
  • Continue the last three steps until the remaining part is zero
  • Append the reversed sequence of digits from the temporary buffer to your output

This is only one way of implementing the logic. Other ways are possible as well - for example, you could build a lookup table of powers of ten, and compute each digit using a combination of integer division and taking the remainder.

Sign up to request clarification or add additional context in comments.

Comments

1

All the code you need, decorated with comments:

if (len == 0) return; /* initialize */ char c = str[0]; int count = 1; /* include terminating '\0', and that will resolve itself! */ for (i = 1; i <= len; i++) { if (str[i] == str[i-1]) { /* continue sequence */ count++; } else { /* end sequence */ printf("%c%d", c, count); /* start new sequence */ c = str[i]; count = 1; } } printf("\n"); /* flush buffer */ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.