简体   繁体   English

空检查与字符串拆分

[英]Empty check with string split

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 =”。

I got result in the vector as below. 我得到如下向量的结果。

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 =

Now I again the sent the resulted strings with separator '='. 现在,我再次发送带有分隔符“ =”的结果字符串。 Its working fine with "l2=lname2". 使用“ l2 = lname2”可以正常工作。 But for "f3=" and "l3=" My separator at last position of the string. 但是对于“ f3 =”和“ l3 =”我的分隔符位于字符串的最后位置。 So I couldn't find the value is null or not . 所以我找不到该值是否为null。 I want to know whether the value ( left side of '=' is name and right side one is value ) is empty or not. 我想知道值(“ =”的左侧是名称,右侧的一个是value)是否为空。 How can i check this. 我该如何检查。

How about boost? 怎么样? I think it is easiest way to split string. 我认为这是分割字符串的最简单方法。

#include <algorithm>
#include <iterator>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;

int main()
{
    string s("f0=fname0&l0=lname0&f1=fname1&l1=lname1&f2=fname2&l2=lname2&f3=&l3=");

    vector<string> v1;    
    split(v1, s, is_any_of("&"), token_compress_on); 
    copy(v1.begin(), v1.end(), ostream_iterator<string>(cout, "\n"));    

    for (auto i : v1) {
        vector<string> v2;
        split(v2, i, is_any_of("="), token_compress_on); 

        copy(v2.begin(), v2.end(), ostream_iterator<string>(cout, "\n===\n"));
    }
}

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)


Edit: 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". 编辑:根据您的评论,然后在标记字符串之前,我将使用string::findstring::replace对其进行修改,以将出现的“ =&” string::replace为“ = hi&”,并将终止的“ =”替换为“ = hi” 。 In that way you'll avoid awkward parsing. 这样,您将避免笨拙的解析。

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). 同样,您将不需要进行两次标记化,因为strtokstrDelimit参数可以为“&=”(一次通过两个定界符)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM