我是 C 新手,正在学习 C90。我正在尝试将字符串解析为命令,但我很难尝试删除白色字符。
我的目标是解析这样的字符串:
NA ME, NAME , 123 456, 124 , 14134, 134. 134 , 1
Run Code Online (Sandbox Code Playgroud)
进入这个:
NA ME,NAME,123 456,124,14134,134. 134,1
Run Code Online (Sandbox Code Playgroud)
因此参数内的白色字符仍然存在,但其他白色字符被删除。
我想过使用strtok,但我仍然想保留逗号,即使有多个连续的逗号。
到目前为止我用过:
void removeWhiteChars(char *s)
{
int i = 0;
int count = 0;
int inNum = 0;
while (s[i])
{
if (isdigit(s[i]))
{
inNum = 1;
}
if (s[i] == ',')
{
inNum = 0;
}
if (!isspace(s[i]) && !inNum)
s[count++] = s[i];
else if (inNum)
{
s[count++] = s[i];
}
++i;
}
s[count] = '\0'; /* adding NULL-terminate to the string */
}
Run Code Online (Sandbox Code Playgroud)
但它只跳过数字,并且不会删除数字后面直到逗号的白色字符,这是完全错误的。
我将不胜感激任何形式的帮助,我已经被这个问题困住了两天了。
每当遇到可能的可跳过空白时,您都需要进行前瞻。下面的函数每次看到空格时都会向前检查它是否以逗号结尾。同样,对于每个逗号,它都会检查并删除所有后续空格。
// Remove elements str[index] to str[index+len] in place
void splice (char * str, int index, int len) {
while (str[index+len]) {
str[index] = str[index+len];
index++;
}
str[index] = 0;
}
void removeWhiteChars (char * str) {
int index=0, seq_len;
while (str[index]) {
if (str[index] == ' ') {
seq_len = 0;
while (str[index+seq_len] == ' ') seq_len++;
if (str[index+seq_len] == ',') {
splice(str, index, seq_len);
}
}
if (str[index] == ',') {
seq_len = 0;
while (str[index+seq_len+1] == ' ') seq_len++;
if (seq_len) {
splice(str, index+1, seq_len);
}
}
index++;
}
}
Run Code Online (Sandbox Code Playgroud)