How to remove commas from a string in C

2019-09-08 03:13发布

Say I have a string of "10, 5, 3" How can I get rid of the commas so the string is just "10 5 3"? Should I be using strtok?

5条回答
倾城 Initia
2楼-- · 2019-09-08 03:40

Here is the program:

#include  <stdio.h>
#include  <conio.h>
    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]) ;

    }

For detailed description you can refer this blog: http://tutorialsschool.com/c-programming/c-programs/remove-comma-from-string.php

查看更多
萌系小妹纸
3楼-- · 2019-09-08 03:46

Create a new string with the same size (+1 for the terminating character) as your current string, copy each character one by one and replace ',' by ' '.

In a for loop you would have something like this :

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

Then after the for loop, do not forget to add '\0' at the end of new_string.

查看更多
霸刀☆藐视天下
4楼-- · 2019-09-08 03:46

How about something like this? (My C is slightly rustyish and I don't have a compiler handy, so pardon any syntax 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';

You could also use a different variable to store the results, but since the result string is guaranteed to be equal or lesser length than the source string, it should be safe to overwrite it as we go.

查看更多
霸刀☆藐视天下
5楼-- · 2019-09-08 03:57

A minor simplification to @melpomene.
Do potential assignment first and then check for the null character.

const char *r = str;
char *w = str;
do {
  if (*r != ',') {
    *w++ = *r;
  }
} while (*r++);
查看更多
ゆ 、 Hurt°
6楼-- · 2019-09-08 04:00
char *r, *w;
for (w = r = str; *r; r++) {
    if (*r != ',') {
        *w++ = *r;
    }
}
*w = '\0';
查看更多
登录 后发表回答