如何拆分字符串使用istringstream与其他分隔符比空格? [英] How to split string using istringstream with other delimiter than whitespace?

查看:511
本文介绍了如何拆分字符串使用istringstream与其他分隔符比空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下技巧使用 istringstream 分割具有空格的字符串。

The following trick using istringstream to split a string with white spaces.

int main() {
    string sentence("Cpp is fun");
    istringstream in(sentence);
    vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
    return 0;
}

有一个类似的技巧来分割一个字符串任何分隔符?例如,Cpp | is | fun中的 |

Is there a similar trick to split a string with any delimiter? For instance, | in "Cpp|is|fun".

推荐答案

一般来说istringstream方法是慢/低效的,需要至少与字符串本身一样多的内存(当你有一个非常大的字符串时会发生什么?)。 C ++字符串工具包库(StrTk)对您的问题有以下解决方案:

Generally speaking the istringstream approach is slow/inefficient and requires at least as much memory as the string itself (what happens when you have a very large string?). The C++ String Toolkit Library (StrTk) has the following solution to your problem:

#include <string>
#include <vector>
#include <deque>
#include "strtk.hpp"
int main()
{
   std::string sentence1( "Cpp is fun" );
   std::vector<std::string> vec;
   strtk::parse(sentence1," ",vec);

   std::string sentence2( "Cpp,is|fun" );
   std::deque<std::string> deq;
   strtk::parse(sentence2,"|,",deq);

   return 0;
}

更多示例可以在这是

这篇关于如何拆分字符串使用istringstream与其他分隔符比空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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