简体   繁体   English

如何使用strstr循环字符串以查找C中的子字符串

[英]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 例如: username:id:password:info

How could I using strstr function in C loop this string to extract the information into different substring? 如何在C中使用strstr函数循环此字符串以将信息提取到不同的子字符串中?

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. 我想使此loopable提取所有子字符串。

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? 如何在C中使用strstr函数循环此字符串以将信息提取到不同的子字符串中?

strstr() isn't the best tool for this task, but it can be used to look for a ":" . strstr()并不是执行此任务的最佳工具,但可用于查找":"
Instead I'd recommend strcspn(string, "\\n") as the goal is to find the next ":" or null character . 相反,我建议strcspn(string, "\\n")因为目标是找到下一个":" null字符

OP'c code is close to forming a loop, yet needs to also handle the last token, which lacks a final ':' . OP'c代码接近形成循环,但还需要处理最后一个标记,该标记缺少最后的':'

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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