Home > Net >  how to copy from char pointer one to anothe char pointer and add chars between
how to copy from char pointer one to anothe char pointer and add chars between

Time:05-21

i want to write function in c that gets char pointer with sentence inside, and in every place there is comma ',' i want to add space ' ' after the comma i write this function

char* add_space_after_comma(char* textArr){
char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));
char* temp = newText;
int i;    
int indexNew=0;
int maxSize = strlen(textArr)-1;
if(newText  == NULL) 
    {
        printf("memory allocation failed \n");
        exit(0);    
    }
for (i = 0; textArr[i] != '\0'; i  , indexNew  ) {
        if(indexNew == maxSize-1){
        
                temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

                if(temp == NULL)
                {
                    printf("memory allocation failed \n");
                    exit(0);
                }
            maxSize= maxSize * ARR_SIZE;
            newText =temp;
        }
        newText[indexNew] = textArr[i];
        if(textArr[i] == ','){
        indexNew  ;
        newText[indexNew] = ' ';
        }
    }
indexNew  ;
newText[indexNew] = '\0';

printf("\nthe new text is: %s\n", newText);
return (char*)newText;
}

but when im trying to run and check it, its print to the screen

the new text is: �����T$ �v���넍�&

how can i write this function rigth?

CodePudding user response:

  • Like pointed out in the comments, if you count the target-character in input string once, all you need is one malloc() for the result. One time parsing of string is efficient than a series of realloc()s.
char* suffixChar_forEach (const char* src, const int slen, const char target, const char suffix) {

    int tgt_count = 0;
    for (int ci = 0; ci < slen;   ci)
        if (target == src[ci])
              tgt_count;

    char* nText = malloc (slen   tgt_count   1);
    if (!nText) {
        perror ("suffixChar_forEach-malloc"); return NULL;
    }
    int nlen = 0;
    for (int ci = 0; ci < slen;   ci) {
        nText[nlen  ] = src[ci];
        if (target == src[ci])
            nText[nlen  ] = suffix;
        }
    nText[nlen] = '\0';

    printf ("\nNew text is: [%s]\n", nText);
    return nText;
}
  • You can also, make the function generic to suffix a char after any given target character.
  • You may also want to get the strlen(nText) from function if necessary.
  • Same function can be used to suffix any char say '-'(hyphen) instead of just ' ' (space) :
int main () {
    char str[] = ",.,.,.,.,.,.,.,.,.,;kl;klkl.,.,.,.,.,.";
    printf ("\nInput: [%s]\n", str);

    char* result = suffixChar_forEach(str, strlen(str), ',', '-');
    if (!result) {
        printf ("ERROR: processing string\n");
        return 1;
    }
    printf ("\nResult: [%s]\n", result);
    free (result);
    return 0;
}

CodePudding user response:

For starters the function parameter should be declared with the qualifier cosnt because the passed string is not changed within the function. The function creates a new string based on the content of the source string.

char * add_space_after_comma( const char* textArr );

The memory allocation in this declaration

char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));

is equivalent to

char* newText=(char *)malloc(strlen(textArr) * sizeof( char * ));

and evidently does not make a sense.

The memory reallocation

temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

is inefficient and also does not make a sense. You need at first to count occurrences of the comma and then at once to allocate an array with the required size.

This incrementing of the index after the for loop

indexNew  ;

is wrong. You need to remove this statement.

And you need to be sure that the passed pointer is indeed points to a string.

The function can be declared and defined as shown in the demonstration program below.

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

char * add_space_after_comma( const char* textArr )
{
    const char c = ',';

    size_t count = 0;

    for ( const char *p = textArr; ( p = strchr( p, c ) ) != NULL;   p )
    {
          count;
    }

    char *result = malloc( strlen( textArr )   1   count );

    if ( result != NULL )
    {
        char *t = result;
        for ( const char *p; ( p = strchr( textArr, c ) ) != NULL; textArr = p   1 )
        {
            size_t n = p - textArr   1;
            memcpy( t, textArr, n );
            t[n  ] = ' ';
            t  =n;
        }

        strcpy( t, textArr );
    }

    return result;
}

int main ()
{
    const char *textArr = "1,2,3,4,5";

    printf( "\"%s\"\n", textArr );

    char *result = add_space_after_comma( textArr );

    if ( result != NULL )
    {
        printf( "\"%s\"\n", result );
    }

    free( result );
}    

The program output is

"1,2,3,4,5"
"1, 2, 3, 4, 5"
  • Related