如何用C中的另一个字符串替换字符串中的字符

时间:2019-02-10 15:00:17

标签: c

假设我有这句话:

  

您好$,欢迎光临!

我必须用名称替换'$',结果应该是:

  

您好,欢迎光临!

现在我这样做了,但是它只复制了名称和短语的第一部分:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/__locale:120:20: Use of undeclared identifier 'LC_COLLATE_MASK'

如何在名称后移动所有元素,以便可以返回完整的字符串?

2 个答案:

答案 0 :(得分:1)

您可以使用sprintf() C字符串打印输出,模拟Prod完成的工作:

  

编辑:您必须包含以下两个标头才能使该功能正常工作:

printf()

您尝试实现的高级实现:

#include <stdlib.h>
#include <memory.h>
  

示例:

char* InsertAt(unsigned start, const char* source, const char* target, const char* with,
               unsigned * position_ret)
{
    const char * pointer = strstr(source, target);
    if (pointer == NULL)
    {
        if (position_ret != NULL)
            *position_ret = UINT_MAX;
        return _strdup(source);
    }
    if (position_ret != NULL)
        *position_ret = (unsigned)(pointer - source);
    char* result = calloc(strlen(source) + strlen(with) + strlen(pointer), sizeof(char));
    sprintf_s(result, strlen(source) + strlen(with) + strlen(pointer), "%.*s%.*s%.*s",
        (signed)(pointer - source), _strdup(source),
        (signed)strlen(with) + 1, _strdup(with),
        (signed)(strlen(pointer) - strlen(target)), _strdup(pointer + strlen(target)));
    return result;
}

答案 1 :(得分:-2)

尝试一下!

#include <stdio.h>
#include <string.h>
char* replace(char* str, char* a, char* b)
{
    int len  = strlen(str);
    int lena = strlen(a), lenb = strlen(b);
    for (char* p = str; p = strstr(p, a); ++p) {
        if (lena != lenb) // shift end as needed
            memmove(p+lenb, p+lena,
                len - (p - str) + lenb);
        memcpy(p, b, lenb);
    }
    return str;
}
int main()
{
    char str[80] = "Hello $,Welcome!";
    printf("%s\n", replace(str, "$", "name"));
    return 0;
}