【问题标题】:Fast way to tokenize a string in c在c中标记字符串的快速方法
【发布时间】:2015-09-14 10:16:55
【问题描述】:

我尝试使用strtok_r,但速度很慢。

现在我有一个 c 字符串 "root.ahmed.andre" 和一个固定分隔符 '.'

如何使用 c 编写更快的搜索标记器?

for (int i = 0;test[i] != 0; i++)
{
    if (test[i] == '.')
    {
        . . .
    }
}

【问题讨论】:

  • 太慢了怎么办? strtok_r() 对字符串进行就地修改——很难比这更快。
  • j_random_hacker,我将如何使用上面的 for 循环标记字符串?
  • i < test[i] != '0' 在 for 循环中应该是 test[i] != 0
  • @mch 还有什么问题请帮忙:)?
  • strtok_r 的源代码开始,修改代码以使用单个分隔符。 sourceforge.net/p/mspgcc/msp430-libc/ci/master/tree/src/string/…

标签: c arrays string algorithm


【解决方案1】:

我不知道strtok_r,但strtok 可能是标记字符串的最快方法。也许你做错了?也许这就是为什么它看起来很慢。

这是在 C 中标记字符串的方法...

#include <string.h>
#include <stdio.h>

int
main (void)
{
    char  string[] = "root.ahmed.andre";
    char *token = strtok (string, ".");

    while (token) {
        // Do what you want with the token here...
        puts (token);

        // Get the next token
        token = strtok (NULL, ".");
    }
}

为了论证,下面的代码将您的字符串标记了 1,000,000 次,并显示了这样做需要多长时间。对我来说,花了 90 毫秒。这真是太快了。

#include <string.h>
#include <stdio.h>
#include <sys/time.h>

int
main (void)
{
    struct timeval tv;
    long int       start;
    long int       end;
    int            i;

    // Get start time in milliseconds
    gettimeofday (&tv, NULL);
    start = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

    for (i = 0; i < 1000000; i++) {
        char  string[] = "root.ahmed.andre";
        char *token = strtok (string, ".");

        while (token) {
            token = strtok (NULL, ".");
        }
    }

    // Get end time in milliseconds
    gettimeofday (&tv, NULL);
    end = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);

    // Print execution time in milliseconds
    printf ("\nDone in %ld ms!\n\n", end - start);

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2016-05-11
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多