gpt4 book ai didi

c - 如何使用模式匹配分割字符串?

转载 作者:行者123 更新时间:2023-11-30 18:35:10 25 4
gpt4 key购买 nike

我有一个像“123-#-#-abc-user-#-#-abcpassword-#-#-123456”这样的字符串,我需要用模式“-#-#-”分割这个字符串来创建一个大批。我使用以下代码来执行此操作

    char buf[5000];
strcpy(buf, "123-#-#-abc-user-#-#-abcpassword-#-#-123456");
int i = 0;
char *p = strtok (buf, "-#-#-");
char *array[5000];

int items = 0;
while (p != NULL)
{
items++;
array[i++] = p;
p = strtok (NULL, "-#-#-");
}

但是由于“abc-user”中的连字符,结果没有得到“123-#-#-abc-user-#-#-abcpassword-#-#-123456”。我期望的是 array[0] 有 123,array[1] 有 abc-user,array[2] 作为 abcpassword 等。是否有其他方法可以使用确切的模式拆分为数组?

最佳答案

strtok() 这里不会产生您期望的确切输出。检查详细信息,C11,第 §7.24.5.8 章

A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. [...]

因此,整个分隔符字符串中存在任何字符都会导致标记化。

您需要寻找strstr()它在更大的字符串中搜索子字符串。再次来自 C11,第 7.24.5.7 章

char *strstr(const char *s1, const char *s2);

The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.

The strstr function returns a pointer to the located string, or a null pointer if the string is not found. [...]

所以你可以

  • 使用函数调用,
  • 获取非空返回指针
  • 执行指针算术以到达您想要的下一个标记。

关于c - 如何使用模式匹配分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47711772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com