文字列を分割してベクトル型データを返すC / C ++のカスタム分割関数
主な内容
文字列を分割するためにsplit関数をカスタマイズする必要があるのはなぜですか?
この記事の当初の意図には、次の2つの点があります。
- C / C ++のSplit関数はstrtok()です。その関数プロトタイプは次のとおりです:
char * strtok(char * str、const char * delimiters);
これはcharポインター型を返します。ベクトル型を直接返す場合は、この記事を読む必要があります。 - 文字列分割の特に単純な方法を提供したい場合、この方法の時間の複雑さはO(n)であり、他の関数は使用されません。
カスタム分割関数はベクトル型データを返しますか?
さらに面倒なことなく、コードに直接移動します。
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
string line;
cin >> line;
vector<string> strArr;
string temp = "";
int i = 0;
while (line[i] != '\0') {
if (line[i] - ',' == 0) {
strArr.push_back(temp);
temp = "";
}
else
temp = temp + line[i];
i++;
}
if(temp.length() > 0)
strArr.push_back(temp);
for (i = 0; i < strArr.size(); i++)
cout << strArr[i] << endl;
system("pause");
return 0;
}