开发者

string parsing occurrence in c

开发者 https://www.devze.com 2022-12-27 02:50 出处:网络
I have a string a开发者_如何转开发s const char *str = \"Hello, this is an example of my string\";

I have a string a开发者_如何转开发s 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


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


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.


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.


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消