用空格分隔字符串 [英] Split string by single spaces

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

问题描述


可能重复:

如何在C ++中分割字符串?





<我需要将一个字符串用单个空格分开,并将其存储到一个字符串数组中。我可以使用istringstream实现此目的,但是我无法实现的是:

I need to split a string by single spaces and store it into an array of strings. I can achieve this using a istringstream, but what I am not being able to achieve is this:

我希望每个空格都终止当前单词。因此,如果连续有两个空格,则数组中的一个元素应为空白。

I want every space to terminate the current word. So, if there are two spaces consecutively, one element of my array should be blank.

例如:

(下划线表示空格)

This_is_a_string.
gets split into:
A[0] = This
A[1] = is
A[2] = a
A[3] = string.

This__is_a_string.
gets split into:
A[0] = This
A[1] = ""
A[2] = is
A[3] = a
A[4] = string.

我该如何实现?

推荐答案

您甚至可以开发自己的split函数(我知道,有点老式):

You can even develop your own split function (I know, little old-fashioned):

size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
    size_t pos = txt.find( ch );
    size_t initialPos = 0;
    strs.clear();

    // Decompose statement
    while( pos != std::string::npos ) {
        strs.push_back( txt.substr( initialPos, pos - initialPos ) );
        initialPos = pos + 1;

        pos = txt.find( ch, initialPos );
    }

    // Add the last one
    strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );

    return strs.size();
}

然后,您只需要使用vector< string>调用它即可。作为参数:

Then you just need to invoke it with a vector<string> as argument:

int main()
{
    std::vector<std::string> v;

    split( "This  is a  test", v, ' ' );
    dump( cout, v );

    return 0;
}

查找在IDEone中分割字符串的代码

希望这会有所帮助。

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

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