tags:

views:

74

answers:

4

I have a string as const char *str = "Hello, this is an example of my string";

How could I get everything after the first comma. So for this instance: this is an example of my string

Thanks

+2  A: 

You can do something similar to what you've posted:

char *a, *b;
int i = 0;
while (a[i] && a[i] != ',')
   i++;
if (a[i] == ',') {
   printf("%s", a + i  + 1);
} else {
   printf("Comma separator not found");
}

Alternatively, you can take a look at strtok and strstr.

With strstr you can do:

char *a = "hello, this is an example of my string";
char *b = ",";
char *c;
c = strstr(a, b);
if (c != NULL)
   printf("%s", c + 1);
else
   printf("Comma separator not found");
Pablo Santa Cruz
A: 
const char *result;
for(result = str; *result; result++)
   if(*result == ',')
   {
      result++;
      break;
   }
//result points to the first character after the comma

After this code, result points to the string starting right after the comma. Or to the final '\0' (empty string), if there is no comma in the string.

slacker
This doesn't distinguish between "no comma" and "comma is the last character of the string".
Adam Rosenfield
@Adam Rosenfield:And should it? "Everything after a nonexistent comma" is "nothing". Of course it depends on the logic of the code it is needed in, but in many cases, if you expect the separator to be there, it is better to return an empty result, than to raise an error condition and require additional code to handle it.
slacker
+2  A: 

Since you want a tail of the original string, there's no need to copy or modify anything, so:

#include <string.h>

...
const char *result = strchr(str, ',');

if (result) {
    printf("Found: %s\n", result+1);
} else {
    printf("Not found\n");
}

If you want ideas how to do it yourself (useful if you later want to do something similar but not identical), take a look at an implementation of strchr.

Steve Jessop
This will get you a string pointing *at* the comma, not at the character after the comma.
Adam Rosenfield
Thanks, I wrote a 1-liner, then changed it to handle a NULL return and lost the +1 in the process. Fixed.
Steve Jessop
Hooray, an answer that doesn't rewrite `strchr()`. Use your standard library, people!
caf
A: 

You have the right idea, the following programs is one way to do it:

#include <stdio.h>
#include <string.h>

static char *comma (char *s) {
    char *cpos = strchr (s, ',');
    if (cpos == NULL)
        return s;
    return cpos + 1;
}

int main (int c, char *v[]) {
    int i;
    if (c >1 )
        for (i = 1; i < c; i++)
            printf ("[%s] -> [%s]\n", v[i], comma (v[i]));
    return 0;
}

It produced the following output:

$ commas hello,there goodbye two,commas,here
[hello,there] -> [there]
[goodbye] -> [goodbye]
[two,commas,here] -> [commas,here]
paxdiablo