gpt4 book ai didi

c - 用字符串或另一个字符替换字符

转载 作者:太空宇宙 更新时间:2023-11-04 08:33:24 26 4
gpt4 key购买 nike

假设我有一个字符数组,就像这样:

abc def ghi jkl ...

单词之间由空格分隔。

我的目标是用我希望的一些其他字符串(字符)替换所有现有空格。例如:

abcMNPdefQRTghiXYZjkl

我考虑创建一个名为 replace 的函数,它可以执行以下操作:

void replace(char *str, int pos, char *rep)
{
//get length of rep
//pos = position of the blank which i want to replace with rep
//code to do the replacement
}

我最初的想法是通过strlen(rep)str的元素右移,然后插入 rep。

这个想法有什么好的或者有其他更好的方法吗?

最佳答案

//replace specified chunks in a string (size-independent, just remember about memory)
void replcnks(char *str, char *cnk1, char *cnk2)
{
char *pos;
int clen1 = strlen(cnk1), clen2 = strlen(cnk2);
while(pos = strstr(str, cnk1))
{
memmove(pos + clen2, pos + clen1, strlen(pos) - clen1 + 1);
memcpy(pos, cnk2, clen2);
}
}

关于c - 用字符串或另一个字符替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27306512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com