简体   繁体   中英

How to loop a string using strstr to find substrings in C

I'm trying to find different substrings of information from a larger string where the information is separated by ":"

For example: username:id:password:info

How could I using strstr function in C loop this string to extract the information into different substring?

So far I've tried something like:

char string[] = "username:id:password:info"
char *endptr;

if((endptr = strstr(string, ":")) != NULL)  {
  char *result = malloc(endptr - string + 1);
  if(result != NULL) {
    memcpy(result, string, (endptr - string));
    result[endptr - string] = '\0';
    username = strdup(result);
    free(result);
  }
}

I want to make this loopable to extract all substrings.

find different substrings of information from a larger string where the information is separated by ":"
How could I using strstr function in C loop this string to extract the information into different substring?

strstr() isn't the best tool for this task, but it can be used to look for a ":" .
Instead I'd recommend strcspn(string, "\\n") as the goal is to find the next ":" or null character .

OP'c code is close to forming a loop, yet needs to also handle the last token, which lacks a final ':' .

void parse_colon(const char *string) {
  while (*string) { // loop until at the end
    size_t len;
    const char *endptr = strstr(string, ":"); // much like OP's code
    if (endptr) {
      len = (size_t) (endptr - string);  // much like OP's code
      endptr++;
    } else {
      len = strlen(string);
      endptr = string + len;
    }
    char *result = malloc(len + 1);
    if (result) {
      memcpy(result, string, len);
      result[len] = '\0';
      puts(result);
      free(result);
    }
    string = endptr;
  }
}

int main(void) {
  parse_colon("username:id:password:info");
}

Output

username
id
password
info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM