在c ++中用空格分隔字符串 [英] Splitting a string by whitespace in c++

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

问题描述


可能的重复项

C ++:如何拆分字符串?

拆分字符串

分割字符串的最佳方法是什么在C ++中的空格?

What is the best way to go about splitting a string up by whitespace in c++?

我想根据tab,空格等来分割,当然忽略多个制表符/空格等。

I'd like to be able to split it based on tab, space, etc. and of course ignore multiple tabs/spaces/etc. in a row as well as not have issues with having those things at the end.

最后,我将最终存储在一个向量中,但我可以很容易地

Ultimately, I am going to end up storing this in a vector, but I can easily convert between data types if there is some easy built-in standard library way of splitting.

我在一个UNIX机器上使用g ++,不是

I am building this on a UNIX machine with g++, not using Microsoft Visual C++

推荐答案

这可能是开放的问题是否最好真正的 easy 方法是将你的字符串放入一个字符串流,然后读取数据:

It may be open to question whether it's best, but one really easy way to do this is to put your string into a stringstream, then read the data back out:

// warning: untested code.
std::vector<std::string> split(std::string const &input) { 
    std::istringstream buffer(input);
    std::vector<std::string> ret;

    std::copy(std::istream_iterator<std::string>(buffer), 
              std::istream_iterator<std::string>(),
              std::back_inserter(ret));
    return ret;
}



如果您愿意,可以初始化 / code>直接来自迭代器:

If you prefer, you can initialize the vector directly from the iterators:

std::vector<std::string> split(std::string const &input) { 
    std::istringstream buffer(input);
    std::vector<std::string> ret((std::istream_iterator<std::string>(buffer)), 
                                 std::istream_iterator<std::string>());
    return ret;
}

应该使用任何合理的C ++编译器。使用C ++ 11,您可以使用括号初始化来清除第二个版本:

Either should work with any reasonable C++ compiler. With C++11, you can clean up the second version a little bit by using brace-initialization instead:

    std::vector<std::string> ret{std::istream_iterator<std::string>(buffer), 
                                 std::istream_iterator<std::string>()};

这篇关于在c ++中用空格分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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