实现“\\”而不是“”(空格)

时间:2015-04-28 19:45:13

标签: c string str-replace

我希望在C中复制字符串时为每个空格替换“\”。 这是呼叫功能系统()所需要的,它将空格标识为“\”。 所以每个空间都应该被替换掉。

#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;
}

这个输出来自“hello \ world\ hi” 如何正确地得到它。需要帮助

2 个答案:

答案 0 :(得分:3)

我认为当你的要求只有一个时,你为每个空间添加了太多\。您还需要更频繁地递增目标指针。最后,没有必要在增加它们的同时延迟循环底部的指针,尽管它没有受到伤害。

以下更正似乎会产生您想要的输出。

#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);
}

输出:

foobar\ bar\ bar

答案 1 :(得分:1)

如果我理解正确,那么该功能可能看起来像

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

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

    return destination;
}

这是一个示范程序

#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;
}

节目输出

Hello world hi
Hello\ world\ hi

我希望该函数不包含任何冗余代码。:)函数循环的主体只包含两个语句。:)