未经测试,但如果isspace()
from<ctype.h>
匹配您要跳过的字符(空格、制表符、换行符),这应该有效:
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (!isspace(TAG[i]))
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
正如评论中所讨论的,此代码应实现'对于一个或多个换行符或空格的每个序列,保留一个空格;通过未更改复制其他字符',再次假设isspace()
是一个合适的函数——isblank()
例如,在标准 C 库中还有 .
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (isspace(TAG[i]))
{
while (i < sizeOfArray && isspace(TAG[i]))
i++;
if (TAG[i] != '\0')
TAG[j++] = ' ';
}
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
现在使用此 SSCCE 进行测试(简短、独立、正确的示例):
#include <ctype.h>
#include <stdio.h>
#include <string.h>
static void squish_whitespace(char *TAG)
{
int sizeOfArray = strlen(TAG);
int i, j;
for (i = j = 0; i < sizeOfArray; i++)
{
if (isspace(TAG[i]))
{
while (i < sizeOfArray && isspace(TAG[i]))
i++;
if (TAG[i] != '\0')
TAG[j++] = ' ';
}
TAG[j++] = TAG[i];
}
TAG[j] = '\0';
}
int main(void)
{
char data[][80] =
{
"abc def ghi",
"abc def \t\t\n\nghi",
"abc def ghi ",
"body {\n" // NB: string concatenation
" background: black;\n"
" color: #80c0c0\n"
" }"
};
enum { NUM_DATA = sizeof(data) / sizeof(data[0]) };
for (size_t i = 0; i < NUM_DATA; i++)
{
printf("Before: [[%s]]\n", data[i]);
squish_whitespace(data[i]);
printf("After: [[%s]]\n", data[i]);
}
return 0;
}
测试数据的输出:
Before: [[abc def ghi]]
After: [[abc def ghi]]
Before: [[abc def
ghi]]
After: [[abc def ghi]]
Before: [[abc def ghi ]]
After: [[abc def ghi]]
Before: [[body {
background: black;
color: #80c0c0
}]]
After: [[body { background: black; color: #80c0c0 }]]