引言
在上一篇的内容中我们通过helloworld,了解到了string的好处,那么在这里我们详细的来认识一下string的魅力吧。
w 藏在什么地方了
#include <iostream>
#include <string>
int main() {
std::string str = "I am the hello world.";
// 在开头吗?
if (str[0] == 'w') { // or using: *(str.begin()) == 'w'
std::cout << "在开头" << std::endl;
}
else if (str[str.size()-1] == 'w') { // or using (*(str.end()-1) == 'w')
std::cout << "在结尾" << std::endl;
}
else {
for (std::string::iterator iter=str.begin(); iter!=str.end(); ++iter) {
if (*iter == 'w') {
std::cout << "找到了, 在第" << iter-str.begin() + 1 << std::endl;
}
}
/* or using below c++11
for (auto c : str) {
if (c == 'w') {
std::cout << "找到了, 在" << iter-str.begin() + 1 << std::endl;
}
}
*/
}
}
在这里,有一点需要注意的是,代码所在文件的编码方式,打个比方说,windows系统内部支持的是gbk的编码方式,如果代码的编码方式是utf-8的话,这里输出的中文就是错误的样子,因此需要确保两者之间的编码方式是一致的。
分离hello world
现在,假如有一个字符串"hello world hello1 world1 hello2 world2",我们需要将这个整串字符串分离成不同的单词,该如何操作呢?
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::string;
using std::cout;
using std::endl;
void seperate(const string &input, const char tag, vector<string> &output) {
string tmp;
for (auto c : input) {
if (c != tag) {
tmp = tmp + c;
}
else if (!tmp.empty()) {
output.push_back(tmp);
tmp.clear();
}
}
// deal with the last word
if (!tmp.empty()) {
output.push_back(tmp);
}
}
int main() {
string str = "hello world hello1 world1 hello2 world2";
vector<string> vec;
seperate(str,' ',vec);
for (auto v : vec) {
cout << v << endl;
}
}