How to remove commas from a string in C

2019-09-08 03:06发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

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++);


回答4:

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:

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