我刚开始学习C和学习C90。我正在尝试将一个字符串解析为一个命令,但我很难尝试删除白色字符。
我的目标是解析这样的字符串:
NA ME, NAME , 123 456, 124 , 14134, 134. 134 , 1 这方面:
NA ME,NAME,123 456,124,14134,134. 134,1所以争论中的白字符仍然存在,但是其他的白字符被移除了。
我考虑使用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 */
}但是它只跳过数字,直到逗号之后才移除白色字符,这是完全错误的。
任何帮助我都会感激的,我已经坚持了两天了。
发布于 2022-05-09 19:50:32
当您遇到可能跳过的空格时,您需要执行查找头。下面的函数,每次它看到一个空格时,都会检查它是否以逗号结尾。同样,对于每个逗号,它检查并删除以下所有空格。
// 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++;
}
}https://stackoverflow.com/questions/72176391
复制相似问题