C删除字符串中的字符
现在,我正在使用此代码在字符串中删除一些字符。
void eliminate(char *str, char ch){
for(; *str != '\0';str++){
if(*str == ch){
strcpy(str, str+1);
str--;
}
}
}
在char *str中,有一些字符串,例如
“ sll $ 6,$ 5,16”
在删除“ $”后,字符串看起来像这样。
“ SLL 6、5、16”
,
但在删除”,“”字符串变得非常奇怪。
“ SLL 6 5 6”
上面的代码有任何问题吗?而且,它仅发生在Linux和在线GDB中。我的窗口笔记本电脑中的VS代码很好地消除了目标char。
Now I'm using this code to delete some char in a string.
void eliminate(char *str, char ch){
for(; *str != '\0';str++){
if(*str == ch){
strcpy(str, str+1);
str--;
}
}
}
In the char *str there are some strings like
"sll $6, $5, 16"
After deleting "$", the string looks like this.
"sll 6, 5, 16"
But after deleting ",", the string became very strange.
"sll 6 5 6"
Is there any problem with the code above? And also, it only happens in Linux and online GDB. VS code in my window laptop eliminates the targeted char very well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于使用函数
strcpy
进行重叠字符串的初学者,如本语句中的重叠字符串会调用未定义的行为。
从C标准(7.23.2.3 strcpy函数)
此语句
当删除字符是字符串的第一个字符时也可以调用未定义的行为。
关于函数声明的一些评论。
这样的功能应遵循C标准字符串功能的一般约定,并返回指针到结果字符串。
另一个一般惯例是,此类功能不检查传递的指针是否等于
null
。将有效的指针传递给字符串是该功能用户的责任。同样,如果用户将传递
'\ 0'
作为要删除的字符,则该函数将对源字符串无能为力,然后将其返回。这是一个演示程序,该程序显示如何声明和定义该函数。
程序输出是
For starters using the function
strcpy
for overlapping strings as in this statementinvokes undefined behavior.
From the C Standard (7.23.2.3 The strcpy function)
This statement
also can invoke undefined behavior when the deleted character is the first character of the string.
Some remarks about the function declaration.
Such a function should follow the general convention of C standard string functions and return pointer to the result string.
Another general convention is that such functions do not check whether the passed pointer is equal to
NULL
. It is the responsibility of the user of the function to pass a valid pointer to a string.Also if the user will pass
'\0'
as the character to be deleted then the function shall do nothing with the source string and just return it.Here is a demonstration program that shows how the function can be declared and defined.
The program output is
正如注释中指出的那样
strcpy()
在用重叠的内存块来应对数据时,这是不安全的。memmove(DST,SRC,LEN)
是使用辅助缓冲区的替代方案,如果src
&DST
内存重叠。您可以简单地跳过角色以消除循环:
As pointed out in comments
strcpy()
is not safe when coping data with overlapping memory blocks.memmove(dst, src, len)
is the alternative which uses an auxiliary buffer in case ofsrc
&dst
memory overlaps.You can simply skip the character to eliminate in a loop:
在不使用显式指针数学的情况下,我们可以在迭代输入字符串时使用两个索引。
i
是每次迭代都会递增的索引,而j
仅在找不到目标字符时递增。如果我们有字符串
char test[] = "hello"
并调用drop_char(test, 'l')
过程如下所示:Without using explicit pointer math, we can use two indices as we iterate over the input string.
i
is an index with increments on each iteration, andj
which only increments when the target character is not found.If we have the string
char test[] = "hello"
and calldrop_char(test, 'l')
the process looks like: