一次只从strtok获取一个令牌

时间:2015-07-17 08:52:48

标签: c token strtok

考虑以下场景,使用两个不同的字符串:

Row1: MyID-MyName-MyAddress-MyNumber-MyNumber2-MyAlias
Row2: MyID-MyName-MyAddress-MyNumber--MyAlias

在第二个示例中,缺少MyNumber2的值。我需要使用strtok()提取每个属性。到目前为止,这是我的代码:

MyID      = strtok (str,  "-"); //where 'str' is the full string
MyName    = strtok (NULL, "-");
MyAddress = strtok (NULL, "-");
MyNumber  = strtok (NULL, "-");
MyNumber2 = strtok (NULL, "-");
MyAlias   = strtok (NULL, "-");

第一个示例运行良好,我能够将每个属性存储在变量中。但是,在第二个例子中,我遇到了麻烦:

当进入变量MyNumber2时,strtok()不会返回空字符串(如我所愿)。相反,它会读取字符串直到与分隔符"-"不匹配的第一个字符,从而忽略字符串中 empty 值的存在。

是否有可能每个分隔符只拆分一次字符串?

2 个答案:

答案 0 :(得分:4)

我认为您应该使用标准函数strchr。例如

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

int main( void )
{
    char s[] = "MyID-MyName-MyAddress-MyNumber--MyAlias";

    for ( char *p = s, *q = s; p != NULL; p = q )
    {
        q = strchr( p, '-' );
        if ( q )
        {            
            printf( "\"%*.*s\"\n", ( int )(q - p ), ( int )( q - p ), p );
            ++q;
        }
        else
        {
            printf( "\"%s\"\n", p );
        }
    }
}    

程序输出

"MyID"
"MyName"
"MyAddress"
"MyNumber"
""
"MyAlias"

答案 1 :(得分:0)

object无法对分隔符之间的空值进行标记。 要弄清楚原因,Please check the first answer here

我和你一样处于同样的境地。我使用public class TagBehavior { public static readonly BindableProperty TagProperty = BindableProperty.CreateAttached<TagBehavior, string>( bindableObject => TagBehavior.GetTag(bindableObject), null, /* default value */ BindingMode.OneWay, null, (bo, old, @new) => TagBehavior.OnCompletedChanged(bo, old, @new), null, null); public static string GetTag(BindableObject bindableObject) { return (string)bindableObject.GetValue(TagBehavior.TagProperty); } public static void SetTag(BindableObject bindingObject, string value) { bindingObject.SetValue(TagBehavior.TagProperty, value); } public static void OnCompletedChanged(BindableObject bindableObject, string oldValue, string newValue) { //var tag = TagBehavior.GetTag(entry); //if (tag != null) //{ // Debug.WriteLine("TODO - Handle tag's value change event"); //} } } 做同样的事情,如下所示:

Strtok

给出了输出:

strstr