本文翻译自:Parse (split) a string in C++ using string delimiter (standard C++)

I am parsing a string in C++ using the following: 我正在使用以下方法在C ++中解析字符串:

string parsed,input="text to be parsed";
stringstream input_stringstream(input);if(getline(input_stringstream,parsed,' '))
{// do some processing.
}

Parsing with a single char delimiter is fine. 使用单个字符定界符进行解析就可以了。 But what if I want to use a string as delimiter. 但是,如果我想使用字符串作为分隔符怎么办?

Example: I want to split: 示例:我想拆分:

scott>=tiger

with >= as delimiter so that I can get scott and tiger. 用> =作为分隔符,这样我就可以得到Scott和Tiger。


#1楼

参考:https://stackoom.com/question/xr81/使用字符串定界符-标准C-在C-中解析-拆分-字符串


#2楼

strtok allows you to pass in multiple chars as delimiters. strtok允许您传入多个字符作为分隔符。 I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters). 我敢打赌,如果您传递“> =”,您的示例字符串将被正确分割(即使>和=被视为单独的分隔符)。

EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize. 如果不想使用c_str()从字符串转换为char *进行编辑,则可以使用substr和find_first_of进行标记化。

string token, mystring("scott>=tiger");
while(token != mystring){token = mystring.substr(0,mystring.find_first_of(">="));mystring = mystring.substr(mystring.find_first_of(">=") + 1);printf("%s ",token.c_str());
}

#3楼

I would use boost::tokenizer . 我会使用boost::tokenizer Here's documentation explaining how to make an appropriate tokenizer function: http://www.boost.org/doc/libs/1_52_0/libs/tokenizer/tokenizerfunction.htm 此处的文档说明了如何使适当的令牌生成器功能: http : //www.boost.org/doc/libs/1_52_0/libs/tokenizer/tokenizerfunction.htm

Here's one that works for your case. 这是适合您情况的一种。

struct my_tokenizer_func
{template<typename It>bool operator()(It& next, It end, std::string & tok){if (next == end)return false;char const * del = ">=";auto pos = std::search(next, end, del, del + 2);tok.assign(next, pos);next = pos;if (next != end)std::advance(next, 2);return true;}void reset() {}
};int main()
{std::string to_be_parsed = "1) one>=2) two>=3) three>=4) four";for (auto i : boost::tokenizer<my_tokenizer_func>(to_be_parsed))std::cout << i << '\n';
}

#4楼

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token. 您可以使用std::string::find()函数查找字符串定界符的位置,然后使用std::string::substr()获得令牌。

Example: 例:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found. find(const string& str, size_t pos = 0)函数返回str中第一次出现str的位置,如果找不到该字符串,则npos

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos . substr(size_t pos = 0, size_t n = npos)函数返回对象的子字符串,从位置pos开始,长度为npos


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length()); ): 如果有多个定界符,则在提取了一个标记后,可以将其删除(包括定界符)以进行后续提取(如果要保留原始字符串,只需使用s = s.substr(pos + delimiter.length()); ):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token. 这样,您可以轻松地循环获取每个令牌。

Complete Example 完整的例子

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {token = s.substr(0, pos);std::cout << token << std::endl;s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output: 输出:

scott
tiger
mushroom

#5楼

This method uses std::string::find without mutating the original string by remembering the beginning and end of the previous substring token. 此方法使用std::string::find而不会通过记住前一个子字符串标记的开始和结尾来改变原始字符串。

#include <iostream>
#include <string>int main()
{std::string s = "scott>=tiger";std::string delim = ">=";auto start = 0U;auto end = s.find(delim);while (end != std::string::npos){std::cout << s.substr(start, end - start) << std::endl;start = end + delim.length();end = s.find(delim, start);}std::cout << s.substr(start, end);
}

#6楼

You can use next function to split string: 您可以使用next函数分割字符串:

vector<string> split(const string& str, const string& delim)
{vector<string> tokens;size_t prev = 0, pos = 0;do{pos = str.find(delim, prev);if (pos == string::npos) pos = str.length();string token = str.substr(prev, pos-prev);if (!token.empty()) tokens.push_back(token);prev = pos + delim.length();}while (pos < str.length() && prev < str.length());return tokens;
}

使用字符串定界符(标准C ++)在C ++中解析(拆分)字符串相关推荐

  1. 在JavaScript中解析查询字符串[重复]

    本文翻译自:Parse query string in JavaScript [duplicate] Possible Duplicate: 可能重复: How can I get query str ...

  2. java split函数的用法,java拆分字符串_java中split拆分字符串函数用法

    摘要 腾兴网为您分享:java中split拆分字符串函数用法,中信期货,掌上电力,星球联盟,淘集集等软件知识,以及韩剧精灵,每日英语听力vip,龙卷风收音机,优衣库,中国平煤神马集团协同办公系统,光晕 ...

  3. [SqlServer]数据库中自定义拆分字符串函数Split()

     经常我们要用到批量操作时都会用到字符串的拆分,郁闷的是SQL Server中却没有自带Split函数,所以我们只能自己动手来解决一下.为了减少和数据库的通讯次数,我们都会利用这种方法来实现批量操作. ...

  4. php字符串加密解密源码,PHP中加密解密字符串函数源代码

    PHP中加密解密字符串函数源代码: /** *功能:对字符串进行加密处理 *参数一:需要加密的内容 *参数二:密钥 */ function passport_encrypt($str,$key){ / ...

  5. mysql 搜索标题中字符串_如何在MySQL表中搜索特定字符串?

    使用等于运算符进行完全匹配-select *from yourTableName where yourColumnName=yourValue; 让我们首先创建一个表-mysql> create ...

  6. java两字符串是否相等_Java与JavaScript中判断两字符串是否相等的区别

    JavaScript是一种常用的脚本语言,这也决定了其相对于其他编程语言显得并不是很规范.在JavaScript中判断两字符串是否相等 直接用==,这与C++里的String类一样.而Java里的等号 ...

  7. qt中解析json字符串的时候出现错误missingNameSeperator

    概述 当解析json字符串,编译代码的时候没有问题,但是当程序调式运行到解析json字符串的时候,即这句: QJsonParseError parseError;QJsonDocument doc = ...

  8. python下列数据中不属于字符串的是_下列数据中,不属于字符串的是( )。 (6.0分)_学小易找答案...

    [单选题]黄酮苷和黄酮苷元一般均能溶解的溶剂是 [其它]跨境物流与海外仓操作 [单选题]在python中,下列流程控制语句没有的是 [单选题]采用碱溶解酸沉淀法提取芦丁,用石灰乳调PH时,应调至 [多 ...

  9. java 将字符串数组清空_在Java中如何将字符串集转换为字符串数组

    详细内容 在Java中将字符串集(Set)转换为字符串数组(String[])的方法有:使用for循环,使用Set.toArray()方法,使用Arrays.copyOf()方法等等.下面我们就来具体 ...

  10. java字符串根据分隔符取值_java中解析含分隔符的字符串

    java中解析含分隔符的字符串 (2010-03-24 16:43:58) 标签: 杂谈 字符串的分隔对于一个以某种分隔符标识字段的字符串,如果想得到串中每个字段项,常用的分隔方法能3种. 设args ...

最新文章

  1. Spark中的内存计算是什么?
  2. python 路径往上一层_Python常用模块之模块、包介绍和相关语法
  3. J2EE (六) 详解 java 中文乱码
  4. CentOS\fedora使用yum update更新时不升级内核的方法
  5. SQLite基本语法
  6. 大数据是如何助德国队打进欧洲杯半决赛的?
  7. Matlab中用到的bsxfun函数
  8. php简单记账本_代理记账的三种方式
  9. 做实体行业现在难吗?
  10. 3.3 rsync同步之ssh隧道方式
  11. 线阵相机工作模式解读
  12. 上海交大计算机专硕学费2018,2018年上海交通大学博士研究生学费与相关奖助政策...
  13. rabbitmq-web-stomp 优化过程
  14. jar解压war文件失败
  15. 计数器—verilog
  16. 片片青艾草,悠悠赤子心
  17. video视频设置第一帧为封面
  18. gt710显卡驱动linux,Ubuntu18.04导入nVidiaGT710显卡
  19. 【软件构造】——课程篇 高屋建瓴,从宏观角度谈软件构造
  20. 微服务项目之电商--19.ElasticSearch基本、高级查询和 过滤、结果过滤、 排序和聚合aggregations

热门文章

  1. DOS 循环 FOR
  2. 总结一下对buffer的学习体会
  3. git warning: LF will be replaced by CRLF in 解决办法 1
  4. Android 自定义控件开发入门(一)
  5. 【常见问题】Can not perform this action after onSaveInstanceState
  6. 图片加载利器Picasso 解析
  7. fiddler下如何将HTTPS转换成HTTP
  8. 用python画出小人发射爱心_小人发射爱心biu简笔画表情-biu小人简笔画表情动态完整版-东坡下载...
  9. uni-app 使用 web-view 页面之间互相跳转、通信
  10. LeetCode题目:两数之和2