gpt4 book ai didi

c - 删除逗号之间的白色字符,但不删除逗号内的内容

转载 作者:行者123 更新时间:2023-12-05 00:42:45 24 4
gpt4 key购买 nike

我是 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 */
}

但是它只跳过数字并且不删除数字后直到逗号的白色字符,这是非常错误的。

我将不胜感激任何形式的帮助,我已经坚持了两天了。

最佳答案

每当遇到可能的可跳过空白时,您都需要进行前瞻。下面的函数,每次看到空格时,都会向前检查它是否以逗号结尾。同样,对于每个逗号,它都会检查并删除所有后续空格。

// 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++;
}
}

关于c - 删除逗号之间的白色字符,但不删除逗号内的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72176391/

24 4 0
文章推荐: javascript - 为什么在以下情况下需要 IIFE?
文章推荐: c++ - 为什么 not_null 还没有进入 C++ 标准?
文章推荐: regex - 如何编写两个对 Regex::replace_all 的调用?
文章推荐: java - 按当前月份排序 List 到最近六个月