c - 如何用C语言中的另一个字符串替换字符串中的字符

标签 c

假设我有这个短语:

Hello $, Welcome!

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

Hello Name, Welcome!

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

char * InsertName(char * string, char * name)
{
    char temp;
    for(int i = 0; i < strlen(string); i++)
    {
        if(string[i] == '$')
        {
            for(int k = i, j = 0; j < strlen(name); j++, k++)
            {
                temp = string[k+2];
                string[k]  = name[j];
                string[k+1] = temp;
            }
            return string;
        }

    }
    return "";
}

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

最佳答案

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

Edit: You will have to include these two headers for this function to work:

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

Example:

#define InsertAtCharacter(src, ch, with) InsertAt(0u, (src), \
                          (char[]){ (char)(ch), '\0' }, (with), NULL)
int main(void)
{
    printf("%s", InsertAtCharacter("Hello $, Welcome!", '$', "Name"));
    return 0;
}

关于c - 如何用C语言中的另一个字符串替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617660/

相关文章:

c - 从文本文件中读取一行并将以空格分隔的数据放入结构中

c - 在没有数组的情况下读取整数和/或字符

c - 是什么导致了这些默认数组值?

c - 如果 sprintf() 缓冲区溢出,写入文件?

c - 在 Mikro C 的同一个 UART channel 中发送多个变量

c - OpenGL视口(viewport)错误

c - 队列:警告:赋值从整数生成指针而不进行强制转换

c - 当非阻塞 send() 仅传输部分数据时,我们可以假设它会在下一次调用时返回 EWOULDBLOCK 吗?

c - multi-pipe() C 程序中的无限循环

c 指向指针的指针,或将列表传递给函数