哇...
最近在练习C++编程,遇到一个题目需要用到字符串分割(类似python的split函数)。C++并没有提供关于这个函数的功能,所以要自己实现。
就在此时,看到字符串流 stringstream 这个高级的类,功能非常强大,如数字与字符串之间的转换。
本文只介绍基于“stringstream+getline”实现字符串分割的功能,建议读者们去详细看看这个类。
http://www.cplusplus.com/reference/sstream/stringstream/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str1 = "/d2/d4/f1";
string str2 = "/d1/../../d2";
string str3 = "hello world hcq!";
string dir;
string dir_list[50];
int i=0;
stringstream ss(str3);
while(getline(ss, dir, ' ')){
dir_list[i] = dir;
cout<<dir_list[i]<<endl;
i++;
}
return 0;
}