Use "\\" instead of "" (space)

I want to replace "\" with every space when copying a string in C. This is required for call function system (), it defines spaces as "\". Therefore, every space must be replaced by this.

#include <stdio.h>

char *my_strcopy(char *destination,char *source){
char *p;
p=destination;

while(*source != '\0'){
    if(*source == ' '){
        *p='\\';
        *p++='\\';
        *p++='\\';
        *p++=' ';
    }
    else{
        *p=*source;
    }
    *p++;
    *source++;
    }
    *p='\0';
    return destination;
}

      

The result is "hello \ world \ hi" how to do it right. help is needed

+3


source to share


2 answers


I think you are adding too much \

for each space when your requirement should only have one. You also incremented the destination pointer more often than necessary. Finally, there is no need to mark the pointers at the bottom of the loop by increasing them, although it doesn't hurt.

The following correction seems to produce the desired result.

#include <stdio.h>

char *my_strcopy(char *destination,char *source){
    char *p;
    p=destination;

    while(*source != '\0'){
        if(*source == ' '){
            *p++='\\';
            *p=' ';
        }
        else{
            *p=*source;
        }
        p++;
        source++;
    }
    *p='\0';
    return destination;
}

int main(){
    char* src = "foobar bar bar";
    char dst[2048];
    my_strcopy(dst, src);
    printf("%s\n", dst);
}

      



Output:

foobar\ bar\ bar

      

+3


source


If I understood correctly, the function might look like

char * my_strcopy( char *destination, const char *source )
{
    char *p = destination;

    do
    {
        if ( *source == ' ' ) *p++ = '\\';
        *p++ = *source;
    } while ( *source++ );

    return destination;
}

      

Here is a demo program

#include <stdio.h>

char * my_strcopy( char *destination, const char *source )
{
    char *p = destination;

    do
    {
        if ( *source == ' ' ) *p++ = '\\';
        *p++ = *source;
    } while ( *source++ );

    return destination;
}

int main() 
{
    char s[] = "Hello world hi";
    char d[sizeof( s ) + 2];

    puts( s );
    puts( my_strcopy( d, s ) );

    return 0;
}

      



Program outputs

Hello world hi
Hello\ world\ hi

      

I hope the function does not contain redundant code. :) The body of the function loop contains only two operators :.)

+1


source







All Articles