开发了strtok替代方案 [英] developed a strtok alternative

查看:211
本文介绍了开发了strtok替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了自己的strtok版本.只是练习使用指针.

I have developed my own version of strtok. Just to practice the use of pointers.

任何人都可以看到与此相关的任何限制,或者无论如何我都可以改善.

Can anyone see any limitations with this or anyway I can improve.

void stvstrtok(const char *source, char *dest, const char token) 
{
    /* Search for the token. */
    int i = 0;
    while(*source)
    {
        *dest++ = *source++;
        if(*source == token)
        {
            source++;
        }
    }
    *dest++ = '\0';
    }

int main(void)
{
    char *long_name = "dog,sat ,on ,the,rug,in ,front,of,the,fire";
    char buffer[sizeof(long_name)/sizeof(*long_name)];

    stvstrtok(long_name, buffer, ',');

    printf("buffer: %s\n", buffer);

   getchar();

   return 0;
}

推荐答案

旁注:令牌"一词通常用于描述返回的字符串部分.分隔符用于描述分隔令牌的事物.因此,为使代码更清晰,您应该将令牌重命名为定界符,将名称重命名为token_dest.

A side note: The word 'token' is usually used to describe the parts of the string that are returned. Delimiter is used to describe the thing that separates the tokens. So to make your code more clear you should rename token to delimiter and rename dest to token_dest.

功能和功能上的差异:

您的函数和strtok之间有一些区别.

There are several differences between your function and strtok.

  • 您的函数要做的只是删除令牌分隔符
  • 您只需调用一次函数即可处理字符串的所有部分.使用strtok,您可以为字符串的每个部分多次调用它(随后多次以NULL作为第一个参数).
  • strtok还会破坏源字符串,而您的代码使用其自己的缓冲区(我认为最好像您一样使用自己的缓冲区).
  • strtok在每次调用后存储下一个标记的位置,其中第一个参数为NULL.然后将此位置用于后续呼叫.但是,这不是线程安全的,您的函数将是线程安全的.
  • strtok可以使用多个不同的定界符,而您的代码仅使用一个定界符.

话虽这么说,但我将为如何提供更好的功能(而不是更接近strtok实现的功能)提供建议.

That being said, I will give suggestions for how to make a better function, not a function that is closer to strtok's implementation.

如何改善您的功能(而不是模拟strtok):

我认为最好进行以下更改:

I think it would be better to make the following changes:

  • 让您的函数简单地返回下一个"令牌
  • 具有* source或* source ==分隔符时,请中断循环
  • 将指针返回到包含下一个标记的源字符串的第一个字符.该指针可用于后续调用.

这篇关于开发了strtok替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆