c - 将字符串中的字符替换为 C 中的字符串

标签 c string replace substring character

让以下示例代码:

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

我想编写一个函数,用 s2 的值替换 '#'。它还为具有新替换版本的新输出字符串动态分配内存。 是否有可能以一种优雅且不复杂的方式,使用大部分内置函数? 我知道如何用字符串中的字符或具有给定子字符串的字符串替换字符,但这似乎打败了我。

最佳答案

您将必须执行几个函数,但是......这里是:

#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() 调用效率低下),但它仅以最“简单”的方式使用标准函数,并且不'本身不做任何“指针”。

关于c - 将字符串中的字符替换为 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672755/

相关文章:

c - 如何从子进程向父进程写入值?

c - 如何将 5 放在 0 旁边 (5 + 0 = 50),而不是在 c 中仅添加 5+0=5?

string - MATLAB 是否提供了从 double 到 string 的无损覆盖函数?

perl - 如何删除文件中的某些换行符

单击计数器以使用 C 代码点亮 LED

c - 为什么 printf 从字面上打印 (null) 以及究竟发生了什么?

javascript - 将日期格式转换为 MM/DD/YYYY

java - 如何在 Java 中解析字符串并查找 double

vim - 全局将所有 ^M 替换为换行符

python - 在 .docx 文件中查找和替换文本 - Python