与字符串分裂的空检查 [英] Empty check with string split

查看:194
本文介绍了与字符串分裂的空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

vector<string> SplitString (string aString,char *sep) 
{  
  vector<string> vec;
  char * cstr,*val,*p;
  string str = aString;
  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());
  p=strtok (cstr,sep);
  while(p!=NULL)
  {    
    vec.push_back(p);  
    p=strtok(NULL,sep);

  }delete[] cstr;return vec; }

这是我的代码。我发送下面的字符串到分隔符'&'

This is my code to string split. I sent the below string to split with separator '&'


f0 = fname0& l0 = lname0& f1 = fname1& l1 = lname1& f2 = fname2& l2 = lname2& f3 =& l3 =。

"f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=".


f0 = fname0 l0 = lname0 f1 = fname1 l1 = lname1 f2 = fname2 l2 = lname2 f3 = l3 =

f0=fname0 l0=lname0 f1=fname1 l1=lname1 f2=fname2 l2=lname2 f3= l3=

现在我再次使用separator'='发送结果字符串。
它的工作正常与l2 = lname2。但是对于f3 =和l3 =我的分隔符在字符串的最后位置。所以我找不到值为null或不。我想知道值('='的左侧是名称,右侧是值)是空的还是不是。我如何检查这个。

Now I again the sent the resulted strings with separator '='. Its working fine with "l2=lname2". But for "f3=" and "l3=" My separator at last position of the string. So I couldn't find the value is null or not . I want to know whether the value ( left side of '=' is name and right side one is value ) is empty or not. How can i check this.

推荐答案

检查您标记字符串的最后一个字符是否实际上是分隔符本身。

Check whether the last character of the string you're tokenising is in fact the seperator itself.

while (p != NULL && p[strlen(p) - 1] != *sep)



编辑:根据您的评论,使用 string :: find string :: replace 来替换出现的=& with= hi&和用= hi终止=。这样你就可以避免尴尬的解析。


Based on your comment, then before tokenising the string I would modify it using string::find and string::replace to replace occurrences of "=&" with "=hi&" and a terminating "=" with "=hi". In that way you'll avoid awkward parsing.

此外,您不需要两次令牌传递,因为<$ c $的 strDelimit 参数c> strtok 可以是& =(两个分隔符在一个通过)。

Also, then you won't need two passes of the tokenising because the strDelimit parameter of strtok can then be "&=" (both delimiters in one pass).

这篇关于与字符串分裂的空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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