STL库函数-分割英语单词

    【例1.11有一段英文由若干单词组成,单词之间用一个空格分隔。编写程序提取其中的所有单词。

#include <iostream>
#include <vector>
#include <String>

using namespace std;

void split(string str,vector<string>& words)
{
    int i = 0;
    int j = str.find(" ");
    while(j != -1)
    {
        string word = str.substr(i,j - i);
        words.push_back(word);
        i = j + 1;
        j = str.find(" ",i);
    }
    if(i < str.length())
    {
        string word = str.substr(i);
        words.push_back(word);
    }
}
int main()
{
    string str = "One day I can find my love!";
    vector<string> words;
    split(str,words);
    vector<string>::iterator it;
    for(it = words.begin(); it != words.end(); it++)
    {
        cout << *it << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Geek_sun/article/details/82529406