让以下示例代码:
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/