Custom split function in C / C ++ to split strings and return vector type data

main content

Why do we need to customize the split function to split the string?

The original intention of this article has the following two points:

  1. The Split function in C / C ++ is strtok (). Its function prototype is as follows:
    char * strtok (char * str, const char * delimiters);
    This returns a char pointer type. If you want to directly return the vector type, you have Must read this article.
  2. Want to provide a particularly simple method of string segmentation, the time complexity of this method is O (n), no other functions are used.

Custom split function returns vector type data?

Without further ado, go directly to the code:

#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;
}
Published 4 original articles · Likes0 · Visits 132

Guess you like

Origin blog.csdn.net/zhangkkit/article/details/105545614