繁体   English   中英

用C中的字符串替换字符串中的字符

[英]Replace a character in a string with a string in C

让下面的示例代码:

char s1[] = "Hey there #!";
char s2[] = "Lou";

我想编写一个函数,将s2的值替换为 它还为具有新替换版本的新输出字符串动态分配内存。 使用大多数内置函数是否可能以一种优雅而简单的方式? 我知道如何用一个字符串中的一个字符替换一个字符,或者使用给定的子字符串替换一个字符串,但是这似乎让我很吃惊。

请查看此内容https://stackoverflow.com/a/32496721/5326843根据此,没有标准函数可以替换字符串。 您必须自己编写。

您将必须通过几个功能,但是...这里是:

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

int main()
{
    char s1[] = "Hey there #!";
    char s2[] = "Lou";

    // Get the resulting length: s1, plus s2,
    // plus terminator, minus one replaced character
    // (the last two cancelling each other out).
    char * s3 = malloc( strlen( s1 ) + strlen( s2 ) );

    // The number of characters of s1 that are not "#".
    // This does search for "any character from the second
    // *string*", so "#", not '#'.
    size_t pos = strcspn( s1, "#" );

    // Copy up to '#' from s1
    strncpy( s3, s1, pos );

    // Append s2
    strcat( s3, s2 );

    // Append from s1 after the '#'
    strcat( s3, s1 + pos + 1 );

    // Check result.
    puts( s3 );
}

这并不是您可以做到的那样高效(尤其是多个strcat()调用效率低下),但是它以最“简单”的方式仅使用标准函数,并且自身不进行任何“指针”操作。

没有单个libc调用,但是可以使用多个libc调用,如下所示,无需动态分配。

    #include <stdio.h>
    #include <string.h>
    char* replace_string(char* str, char* find, char* replace_str)
    {
        int len  = strlen(str);
        int len_find = strlen(find), len_replace = strlen(replace_str);
        for (char* ptr = str; ptr = strstr(ptr, find); ++ptr) {
            if (len_find != len_replace) 
                memmove(ptr+len_replace, ptr+len_find,
                    len - (ptr - str) + len_replace);
            memcpy(ptr, replace_str, len_replace);
        }
        return str;
    }

    int main(void)
    {
        char str[] = "Hey there #!";
        char str_replace[] = "Lou";
        printf("%s\n", replace_string(str, "#", str_replace));
        return 0;
    }

输出:

Hey there Lou!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM