Home > front end >  Doubling all occurrences of a specific character in a string
Doubling all occurrences of a specific character in a string

Time:11-16

I want to write a C program, that returns a new string allocated on the heap. This string is obtained by doubling all occurrences of “c” in a string (“abcdc” becomes “abccdcc” after doubling “c”).

This is my code and I don't really see where the problem is to fix it!

    size_t taille = stringLength(str);
    size_t k=0;
    size_t q=0;
    
    while (*str!='\0') 
    {
        if (*str == c)
        {
            k=k 1;
        }
          str;
    }
    
    char *nouvelle=malloc(taille 1 k);
    
    int i,j= 0;
    while(*str !='\0')
    {
        
        if (str[i] != c)
        {
            j=i;
            nouvelle[j]=str[i];
        }
        else
        {
            j=i;
              q;
            nouvelle[j]=str[i];
            j=i q;
            nouvelle[j  ]=str[i];
            
        }
          i;
    }
    nouvelle[taille 1 k]='\0';
    return nouvelle;
}

CodePudding user response:

There are two problems with your code.

The first one is that after this while loop

while (*str!='\0') 
{
    if (*str == c)
    {
        k=k 1;
    }
      str;
}

the pointer str points to the end of the string that is to the terminating zero character '\0'.

The second one is that you are using the uninitialized variable i

int i,j= 0;
while(*str !='\0')
{
    
    if (str[i] != c)
    {
        j=i;
        //..

This declaration

int i,j= 0;

is not the same as

int i = 0,j= 0;

That is only the variable j is initialized by 0.

And the statement

j = i;

does not make sense.

Also it is unclear whether c denotes a variable or the character 'c'. If you mean the character 'c' then you need to write at least like

if (*str == 'c')

You could define the function for example the following way as shown in the demonstration program below.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * duplicate_char( const char *s, char c )
{
    size_t n = 0;

    for (const char *p = s; *p;   p)
    {
        if (*p == c)   n;
    }

    char *nouvelle = malloc( strlen( s )   n   1 );

    if (nouvelle)
    {
        if (n == 0)
        {
            strcpy( nouvelle, s );
        }
        else
        {
            char *p = nouvelle;

            while (*s)
            {
                *p   = *s  ;

                if (p[-1] == c) *p   = c;
            }

            *p = '\0';
        }
    }

    return nouvelle;
}

int main( void )
{
    char *nouvelle = duplicate_char( "abcdc", 'c' );

    if (nouvelle != NULL) puts( nouvelle );

    free( nouvelle );
}

The program output is

abccdcc

If you want to use your own function stringLength instead of the standard C function strlen then it can look like

size_t stringLength( const char *s )
{
    const char *p = s;

    while ( *p )   p;

    return p - s;
}
  • Related