【发布时间】:2017-10-26 15:20:34
【问题描述】:
我正在实现一个函数,给定一个字符串、一个字符和另一个字符串(因为现在我们可以称它为“子字符串”);将子字符串放在字符串中字符所在的任何位置。 为了更好地解释我,给定这些参数,这是函数应该返回的(伪代码):
func ("aeiou", 'i', "hello") -> aehelloou
我正在使用来自string.h lib 的一些函数。我已经测试了它,结果非常好:
char *somestring= "this$ is a tes$t wawawa$wa";
printf("%s", strcinsert(somestring, '$', "WHAT?!") );
Outputs: thisWHAT?! is a tesWHAT?!t wawawaWHAT?!wa
所以现在一切都很好。问题是当我尝试对例如这个字符串做同样的事情时:
char *somestring= "this \"is a test\" wawawawa";
printf("%s", strcinsert(somestring, '"', "\\\"") );
因为我想将每个 " 更改为 \" 。当我这样做时,PC 崩溃了。我不知道为什么,但它停止工作然后关闭。我已经了解了string.h lib 的某些功能的不良行为,但我找不到任何相关信息,非常感谢任何帮助。
我的代码:
#define salloc(size) (str)malloc(size+1) //i'm lazy
typedef char* str;
str strcinsert (str string, char flag, str substring)
{
int nflag= 0; //this is the number of times the character appears
for (int i= 0; i<strlen(string); i++)
if (string[i]==flag)
nflag++;
str new=string;
int pos;
while (strchr(string, flag)) //since when its not found returns NULL
{
new= salloc(strlen(string)+nflag*strlen(substring)-nflag);
pos= strlen(string)-strlen(strchr(string, flag));
strncpy(new, string, pos);
strcat(new, substring);
strcat(new, string+pos+1);
string= new;
}
return new;
}
感谢您的帮助!
【问题讨论】:
-
typedef char* str; -
那个宏——也很讨厌。
-
顺便说一句,使用
new作为标识符肯定会使这段代码对 C++ 无效,因此转换malloc()的结果充其量是多余的。 -
该死的@chux 是真的
-
您还应该知道,与 Python 不同,
strlen实际上并不是免费的。您应该缓存结果,而不是一遍又一遍地调用它。