![](/img/trans.png)
[英]Replacing a substring in a string with another substring in c using array of pointers to string
[英]Replacing a substring with another string in C
我正在编写代码,用其值替换所有MACROS。 如果我的宏MAX的值为1000,并且在代码中必须将其替换为1000(我假设一个情况是,如果MACROS是一行中的第一个单词,那么在该行中我们将不会替换MACROS,并且这种情况下我们将得到不同的处理。
//Code to replace MACROS BY THEIR VALUES
//line contains the actual one line of the code.
//line is initialized to contain as maximum number of charectos(say 100).
//SrcStr is the macro and destStr is its value.
//This block will be looped for all lines.
char* p;
p = strstr(line,srcStr);
if(p != NULL) //if the srcString is found
{
if(strlen(p) != strlen(line)) //special case
{
if( isalnum(*(p-1)) == 0 && isalnum( *(p+strlen(srcStr)))==0 )
// if the next char and prev char to our macro is not a alphabets or digits
{
/*As answered by medo42 (below)*/
memmove(p+strlen(destStr), p+strlen(srcStr),strlen(p+strlen(srcStr)+1);
memcpy(p,destStr,strlen(destStr));
}
}
else
{/* handle differently*/}
}
由于我是第一次使用memmove
和memcopy
,因此我怀疑上面的代码是否稳定并且可以正常工作。
上面的代码正确吗? 上面的代码对于所有输入情况都是稳定的吗?
我至少看到三个问题:
sizeof(p)
(例如4),而应使用strlen(line) - (p + strlen(p) - line)
if(strlen(p) != strlen(line))
为什么不在这里简单地使用if(p != line)
? 那应该是等效的,更容易理解和更快(strlen扫描整个字符串)。
isalnum(...) == 0
可能是个人喜好,但我将该表达式写为!isalnum(...)
因为这样更容易理解其含义。
memmove(p+(strlen(destStr)-strlen(srcStr)),p,sizeof(p));
在我看来,这是错误的。 它将根据指针大小移动许多字符,这没有任何意义,并且如果srcStr长于destStr,则移动的目标可能是行缓冲区开始之前的位置。 如果要移动行的其余部分以适应更改的长度,请尝试以下操作: memmove(p+strlen(destStr), p+strlen(srcStr), strlen(p+strlen(srcStr)+1);
+ 1对于移动空终止符也很重要,当然,您需要确保行缓冲区实际提供了足够的空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.