C压缩字符串中的空格

时间:2024-04-29 01:59:22

使用纯C语言,去除一个字符串开头和结尾的空格,内部若有连续空格只保留一个。

 C Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void trimSpace(char *pStr)
{
    if(NULL == pStr) return;

;
    ;
    int strLen = strlen(pStr);

/**< 去除字符串前面的空格 */
    while(pStr[high] == ' ' && high < strLen)
    {
        ++high;
    }

while(high < strLen)
    {

if(pStr[high] == ' ') // 读取连续空格,并压缩为一个空格
        {
            pStr[low++] = ' ';
            while(pStr[high] == ' ' && high < strLen)
            {
                ++high;
            }
        }
        else // 读取连续单词
        {
            while(pStr[high] != ' ' && high < strLen)
            {
                pStr[low++] = pStr[high++];
            }
        }
    }
    /**< 去除字符串末尾的空格 */
    ] == ' ')
    {
        pStr[low - ] = '\0';
    }
    else
    {
        pStr[low] = '\0';
    }
}

int main()
{
    ;
    char *pStr = malloc(sizeof(char) * size);
    gets(pStr);
    trimSpace(pStr);
    printf("%s", pStr);
    free(pStr);

;
}