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

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

我试图从一个较大的字符串中找到不同的信息子字符串,其中信息由 ":"

分隔

例如:用户名:id:密码:信息

我如何在 C 中使用 strstr 函数循环此字符串以将信息提取到不同的子字符串中?

到目前为止,我已经尝试过类似的方法:

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] = '[=10=]';
    username = strdup(result);
    free(result);
  }
}

我想让这个可循环以提取所有子字符串。

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() 不是完成此任务的最佳工具,但它可用于查找 ":".
相反,我建议 strcspn(string, "\n") 因为目标是找到下一个 ":" 空字符 .

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] = '[=10=]';
      puts(result);
      free(result);
    }
    string = endptr;
  }
}

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

输出

username
id
password
info