テストされていませんが、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';
コメントで説明されているように、このコードは「1 つ以上の改行またはスペースのシーケンスごとに、1 つのスペースを保持する」を実装する必要があります。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 }]]