0

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?

mperic
  • 118
  • 9
  • 9
    If there's only one comma in the string, then that same comma is found whether you are looking for the "first" or the "last" of that character. – Steve Friedl Nov 26 '19 at 03:06

2 Answers2

3

It sounds like you want strtok instead:

char *name = strtok(input, ",");
char *value = strtok(NULL, ",");
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • I think this works, thank you. I mistakenly thought that the only difference between strchr and strrchr was that one started from index 0 and the other started at index length - 1. – mperic Nov 26 '19 at 03:13
  • 3
    That _is_ the only difference - `strchr` starts at index 0 and goes forward, and `strrchr` starts at `strlen(s) - 1` and goes backwards. As @SteveFriedl points out, if you only have one `,` then these two will find the same result. They only really give you the position of the character but won't split the string for you - `strtok` does and that makes it more useful here. – nneonneo Nov 26 '19 at 03:16
0

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);
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42