Possible Duplicate:
How do I replace multiple spaces with a single space in C?
我在 c 中有一个字符串,可以包含两个连续的空格。我想用一个空格删除两个连续的空格。我怎样才能做到这一点?请帮忙。
最佳答案
如果字符串中仅出现两个连续空格,则可以使用 strstr()
和 memmove()
:
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "a string with two spaces";
char* two_spaces_ptr = strstr(s, " ");
printf("[%s]\n", s);
if (two_spaces_ptr)
{
memmove(two_spaces_ptr + 1,
two_spaces_ptr + 2,
strlen(two_spaces_ptr + 2) + 1); /* +1 to copy the NULL. */
}
printf("[%s]\n", s);
return 0;
}
输出:
[a string with two spaces]
[a string with two spaces]
memmove()
的 C 标准规定:
The memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1.
编辑:
更新了答案以使用 memmove()
,而不是导致未定义行为的 strcpy()
。
关于c - c中连续两个空格替换为一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9818807/