c - c中连续两个空格替换为一个空格

标签 c

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/

相关文章:

c - 使二维数组和一维数组的地址相等

c++ - 流式文件增量编码/解码

c - C中有取反二进制数的函数吗?

c - 在 Xlib 中,如何在事件发生之前制作动画?

c - 为什么在尝试显示整数内存位置时会出现 clang 错误?

c - 程序终止后变量保留值,如何防止? C

java - 如何在native中写/读直接的ByteBuffer?

c - 接收段错误: 11

c - Linux (GLNXA64) 使用 mxCreateUninitNumericMatrix R2013b

c - 尝试学习 C 中的动态内存分配