【C++】基于“stringstream+getline”实现字符串分割(split)

哇...

最近在练习C++编程,遇到一个题目需要用到字符串分割(类似python的split函数)。C++并没有提供关于这个函数的功能,所以要自己实现。

就在此时,看到字符串流 stringstream 这个高级的类,功能非常强大,如数字与字符串之间的转换。

本文只介绍基于“stringstream+getline”实现字符串分割的功能,建议读者们去详细看看这个类。

http://www.cplusplus.com/reference/sstream/stringstream/


#include 
#include 
#include 

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<
【C++】基于“stringstream+getline”实现字符串分割(split)_第1张图片


附上大神的“CCF CSP 201604-3 路径解析”代码:

本人的思路是构建路径对应的树(左孩子,右兄弟的数据结构),然后遍历一下得到所有绝对路径。

#include 
#include 
#include 
#include 
#include 
using namespace std;

#define MAX_NUM 11

int N;
string current, relative[MAX_NUM];
string path[MAX_NUM];
vector stk, newStk;

void input(){
	ifstream in_data;
	in_data.open("./data.txt");
	in_data >> N;
	in_data >> current;
	
	for(int i=0; i> relative[i];
	}
}

void printStack(const vector &stk) {
    for(int i=0; i &stk, string path) {
    stringstream ss(path);
    string dir;
    bool first = true;
    while(getline(ss, dir, '/')) {
//    	cout<();
        }
        else if(dir == "..") {
            if(!stk.empty()){
            	stk.pop_back();
			}
        }
        else if(dir == ".") {}
        else {
            stk.push_back(dir);
        }
        first = false;
    }
}

int main() {
//    int N;
//    cin >> N;
//    string current, relative;
//    cin >> current;
	input();
    vector stk, newStk;
    formalize(stk, current);
//    cin.ignore();
    for(int i=0; i

你可能感兴趣的:(【C++】,C++,数据结构)