Strchr and strrchr returning same result

359 Views Asked by At

For some reason, whether I try strchr or strrchr, I get the same value returned. I have no idea why.

Here is the segment of code giving me trouble:

      printf("Enter a data point (-1 to stop input):\n");
      fgets(input, 50, stdin);
      char *name = strrchr(input, ',');
      if(name)
      {
         printf("%s", name);
      }

The input is Jane Austen, 6, and I am trying to separate it into two strings: one before the comma and one after the comma. However, my use of strrchr(input, ','); or strchr(input, ','); seems pointless, as my output is ALWAYS , 6. Can someone explain why?

2

There are 2 best solutions below

2
nneonneo On BEST ANSWER

It sounds like you want strtok instead:

char *name = strtok(input, ",");
char *value = strtok(NULL, ",");
2
ChuckCottrill On

Some languages provide a string function split that takes a string or regular expression and splits the string into a list of substrings separated by the delimiter (python, ruby, perl). It is not too difficult to construct such a split function, especially if you just split on a single character.

char** split(char* string, char delim);

You will also want a string join function, and a function to cleanup the allocated space.

char* split_join(char** splitray, char* buffer);
void split_free(char** splitray);