C++学习笔记(六)~提取字符串中每一个单词【istringstream 字符流】
【摘要】 前言
题目要求:提取一个字符串中所有的单词,例如“my name is haihong”,返回“my”“name”“is”“haihong”。
解答
方法一:
#include <iostream>
#include<vector>
using...
前言
题目要求:提取一个字符串中所有的单词,例如“my name is haihong”,返回“my”“name”“is”“haihong”。
解答
方法一:
#include <iostream>
#include<vector>
using namespace std;
vector<string> word_1(string s)
{ vector<string> ans; for(int i=0;i<s.size();++i) { int j=i; string temp; while (s[j]!=' ') { ++j; } temp=s.substr(i,j-i); ans.push_back(temp); i=j; } return ans;
}
int main()
{ vector<string> s; s=word_1("my name is haihong"); for(int i=0;i<s.size();++i) cout<<s[i]<<endl; return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
运行结果
方法二:
#include <iostream>
#include<vector>
using namespace std;
vector<string> word_2(string s)
{ int start = 0; vector<string> res; for(int i = 0;i<s.size();i++){ if(s[i] == ' '){ string temp = s.substr(start,i-start); res.push_back(temp); start = i+1; } } // 补上最后一个单词 string temp = s.substr(start,s.size()-start); res.push_back(temp); return res;
}
int main()
{ vector<string> s; s=word_2(" my name is haihong"); for(int i=0;i<s.size();++i) cout<<s[i]<<endl; return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
运行结果
注意:以上只适合于:第一个和最后一个字符不是空格、每个单词之间只有一个空格
方法三:
#include <iostream>
#include<vector>
#include<sstream>
using namespace std;
vector<string> word_4(string s)
{ vector<string> res; for(int i=0;i<s.size();++i) { while(s[i]==' ') ++i; int j=i; while(s[j]!=' '&&j<s.size())// 注意:这里需要加上j<s.size() ++j; string temp=s.substr(i,j-i); res.push_back(temp); i=j; } return res;
}
int main()
{ vector<string> s; s=word_4(" my name is haihong "); for(int i=0;i<s.size();++i) cout<<s[i]<<endl; return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
运行结果
方法四:【istringstream 字符流】
#include <iostream>
#include<vector>
#include<sstream>// 使用istringstream就需要引入 sstream
using namespace std;
vector<string> word_3(string s)
{ vector<string> res; istringstream words(s); string word; while(words>>word) { res.push_back(word); } return res;
}
int main()
{ vector<string> s; s=word_3(" my name is haihong"); for(int i=0;i<s.size();++i) cout<<s[i]<<endl; return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
运行结果
注意:方法三、四适用于任意字符串。
文章来源: haihong.blog.csdn.net,作者:海轰Pro,版权归原作者所有,如需转载,请联系作者。
原文链接:haihong.blog.csdn.net/article/details/108500538
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)