如何从C中的字符串中删除逗号

说我有一个“10,5,3”的字符串如何摆脱逗号,所以字符串只是“10 5 3”? 我应该使用strtok吗?

 char *r, *w; for (w = r = str; *r; r++) { if (*r != ',') { *w++ = *r; } } *w = '\0'; 

创建一个具有相同大小的新字符串(终止字符为+1)作为当前字符串,逐个复制每个字符并将’,’替换为”。

for循环中你会有这样的东西:

 if (old_string[i] == ',') new_string[i] = ' '; else new_string[i] = old_string[i]; i++; 

然后在for循环之后,不要忘记在new_string的末尾添加’\ 0’。

@melpomene的一个小简化。
首先进行潜在的分配,然后检查空字符。

 const char *r = str; char *w = str; do { if (*r != ',') { *w++ = *r; } } while (*r++); 

这样的事怎么样? (我的C略显生锈,我没有编译器方便,所以请原谅任何语法bloopers)

 char *string_with_commas = getStringWithCommas(); char *ptr1, *ptr2; ptr1 = ptr2 = string_with_commas; while(*ptr2 != '\0') { if(*ptr2 != ',') *ptr1++ = *ptr2++; else *ptr2++; } *ptr1 = '\0'; 

您也可以使用不同的变量来存储结果,但由于结果字符串保证与源字符串相等或更短,因此我们可以安全地覆盖它。

这是程序:

 #include  #include  int main() { int i ; char n[20] ; printf("Enter a number. ") ; gets(n) ; printf("Number without comma is:") ; for(i=0 ; n[i]!='\0' ; i++) if(n[i] != ',') putchar(n[i]) ; } 

有关详细说明,请参阅此博客: http : //tutorialsschool.com/c-programming/c-programs/remove-comma-from-string.php