Cut string c++: In the previous article, we have discussed about How to remove Substring from a String in C++. Let us learn how to split a string using String and character as Delimiter in C++ Program.
Split a string using another string and character as Delimiter
Split string by delimiter c++: In this article we see 2 different ways to split a std::string in C++.
Splitting a string using a char as delimiter :
C++ split string by delimiter: Here the passed string will be converted into stringstream and from that each word will be fetched using getline method.
#include <string> #include <iostream> #include <sstream> #include <vector> // Using delimeter as a character. std::vector<std::string> split(std::string strToSplit, char delimeter) { std::stringstream ss(strToSplit); std::string item; std::vector<std::string> splittedStrings; while (std::getline(ss, item, delimeter)) { splittedStrings.push_back(item); } return splittedStrings; } int main() { std::string str = "You are studying from BtechGeeks"; // Spliting the string by '' std::vector<std::string> splittedStrings = split(str, ' '); for(int i = 0; i < splittedStrings.size() ; i++) std::cout<<splittedStrings[i]<<std::endl; return 0; }
Output : You are studying from BtechGeeks
Splitting a string by another string as delimiter :
C++ split string by character: Like in above we splitted using character delimiter here we will split using another string. So, for this we have to use another std::string as delimiter.
#include <string> #include <vector> #include <sstream> #include <iostream> //By using delimeter as an another string std::vector<std::string> split(std::string stringToBeSplitted, std::string delimeter) { std::vector<std::string> splittedString; int startIndex = 0; int endIndex = 0; while( (endIndex = stringToBeSplitted.find(delimeter, startIndex)) < stringToBeSplitted.size() ) { std::string val = stringToBeSplitted.substr(startIndex, endIndex - startIndex); splittedString.push_back(val); startIndex = endIndex + delimeter.size(); } if(startIndex < stringToBeSplitted.size()) { std::string val = stringToBeSplitted.substr(startIndex); splittedString.push_back(val); } return splittedString; } int main() { std::string str = "You are studying from BtechGeeks"; // Spliting the string by an another std::string std::vector<std::string> splittedStrings_2 = split(str, "studying"); for(int i = 0; i < splittedStrings_2.size() ; i++) std::cout<<splittedStrings_2[i]<<std::endl; return 0; }
Output : You are from BtechGeeks