1. 程式人生 > >【C++】基於“stringstream+getline”實現字串分割(split)

【C++】基於“stringstream+getline”實現字串分割(split)

哇...

最近在練習C++程式設計,遇到一個題目需要用到字串分割(類似python的split函式)。C++並沒有提供關於這個函式的功能,所以要自己實現。

就在此時,看到字串流 stringstream 這個高階的類,功能非常強大,如數字與字串之間的轉換。

本文只介紹基於“stringstream+getline”實現字串分割的功能,建議讀者們去詳細看看這個類。

#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;
} 

附上大神的“CCF CSP 201604-3 路徑解析”程式碼:

本人的思路是構建路徑對應的樹(左孩子,右兄弟的資料結構),然後遍歷一下得到所有絕對路徑。

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;

#define MAX_NUM 11

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

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

void printStack(const vector<string> &stk) {
    for(int i=0; i<stk.size(); i++) {
        cout << "/" << stk[i];
    }
    if(stk.empty()) cout << "/";
    cout << "\n";
}

void formalize(vector<string> &stk, string path) {
    stringstream ss(path);
    string dir;
    bool first = true;
    while(getline(ss, dir, '/')) {
//    	cout<<dir<<"|||"<<&stk<<endl;
        if(dir.empty()) {
            if (first) stk = vector<string>();
        }
        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<string> stk, newStk;
    formalize(stk, current);
//    cin.ignore();
    for(int i=0; i<N; i++){
    	newStk = stk;
        formalize(newStk, relative[i]);
        printStack(newStk);
	}
}