Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add space between the characters if two consecutive characters are equal in c?

I need to add add space if two consecutive characters are same.

For example:
input:

ttjjjiibbbbhhhhhppuuuu

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

t tjjji ibbbbhhhhhp puuuu

If the two consecutive characters are same then need to print space between two consecutive characters….if the consecutive characters are greater than two no need to add space.

My code:

#include <stdio.h>
#include <string.h>
int main()
{
    char s[100]="ttjjjiibbbbhhhhhppuuuu";
    for(int i=0;i<strlen(s);i++){
      if(s[i]!=s[i-1] && s[i]==s[i+1]){
        s[i+1]=' ';
    }
}
printf("%s",s);
}

my output:

t j ji b b h h hp u u 

What mistake i made??

>Solution :

Your primary mistake is writing to your input when the string needs to grow. That’s not going to work well and is hard to debug.

This is typical of C Code: measure once, process once. Same-ish code appears twice.

Variables:

int counter;
char *ptr1;
char *ptr2;
char *t;

Step 1: measure

for (ptr1 = s; *ptr1; ptr1++)
{
    ++counter;
    if (ptr1[0] == ptr1[1] && ptr1[0] != ptr1[2] && (ptr1 == s || ptr1[-1] != ptr1[0]))
        ++counter;
}

Step 2: copy and process

t = malloc(counter + 1);
for (ptr1 = s, ptr2 = t; *ptr1; ptr1++)
{
    *ptr2++ = *ptr1;
    if (ptr1[0] == ptr1[1] && ptr1[0] != ptr1[2] && (ptr1 == s || ptr1[-1] != ptr1[0]))
        *ptr2++ = ' ';
}
ptr2[0] = '\0';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading