有没有办法在 C 中将字符串拆分为多个字符?

发布于 2024-11-30 00:07:22 字数 236 浏览 0 评论 0原文

C 中是否有一种方法可以在分隔符长度超过一个字符的情况下分割字符串(使用 strtok 或任何其他方式)?我正在寻找这样的东西:

char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");

我希望它不会分割字符串,因为逗号和 W 之间没有空格。有没有办法做到这一点?

Is there a way in C to split a string (using strtok or any other way) where the delimiter is more than one character in length? I'm looking for something like this:

char a[14] = "Hello,World!";
char *b[2];
b[0] = strtok(a, ", ");
b[1] = strtok(NULL, ", ");

I want this to not split the string because there is no space between the comma and the W. Is there a way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

染墨丶若流云 2024-12-07 00:07:22

您可以重复调用 substr 来查找出现的情况边界字符串并沿着结果分割。找到结果后,将指针前进子字符串的长度并再次搜索。

You could just repeatedly call substr to find occurrences of your boundary string and split along the results. After you found a result, advance the pointer by the length of the substring and search again.

掩耳倾听 2024-12-07 00:07:22

您可以使用 char * strstr(const char *haystack, const char *needle) 在字符串中定位分隔符字符串。

char a[14] = "Hello,World!";
char b[2] = ", ";
char *start = a;
char *delim;
do {
    delim = strstr(start, b);
    // string between start and delim (or end of string if delim is NULL).
    start = delim + 2; // Use lengthof your b string.
} while (delim);

You can use char * strstr(const char *haystack, const char *needle) to locate your delimiter string within your string.

char a[14] = "Hello,World!";
char b[2] = ", ";
char *start = a;
char *delim;
do {
    delim = strstr(start, b);
    // string between start and delim (or end of string if delim is NULL).
    start = delim + 2; // Use lengthof your b string.
} while (delim);
情仇皆在手 2024-12-07 00:07:22

也许是这样的?不保证可以编译。 ;)

char* strstrtok(char *haystack, char *needle) {
    static char *remaining = null;
    char *working;

    if(haystack)
         working = haystack;
    else if(remaining)
         working = remaining;
    else
         return NULL;

    char *result = working;
    if(result = strstr(working, needle))
        remaining = working + strlen(needle) + 1;

    return result;
}

Something like this maybe? No guarantees that this compiles. ;)

char* strstrtok(char *haystack, char *needle) {
    static char *remaining = null;
    char *working;

    if(haystack)
         working = haystack;
    else if(remaining)
         working = remaining;
    else
         return NULL;

    char *result = working;
    if(result = strstr(working, needle))
        remaining = working + strlen(needle) + 1;

    return result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文