If I have a const char * of "bad,cold,new" how can I count just the number of commas? Do I need to convert it to string? If so, how do I do that? Do I need to convert all the commas to zeros first? How do i do that?

9 Years
Discussion Span
Last Post by balla4eva33

just declare another pointer to be the same as the original and increment it until it reaches the end of the string. Along the way count the number of commas etc. You could use the original pointer but its better not to so that you don't destroy the address of the original string.

const char* original = "bad,cold,new";
char *dup = original;
if( *dup == ',')
//   do something

So what do I put in place of "//do something" if, for example, I want to change every comma to a zero?

',' = '0'; //???


>>I want to change every comma to a zero?
You can not do that -- the const keyword means the string can not be changed. All you can do is increment the pointer and look at the contents. If you want to change the string then copy it to another char buffer. After copying the string then you can do this to change it

if( *ptr == ',')
    *ptr = '0';

where ptr is a pointer to the copy of the string.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.