split string on character vector C++
To split a string on a character in C++, you can use the std::getline
function from the <string>
library. Here are the steps to do it:
- Include the necessary header files:
#include <iostream>
#include <string>
#include <vector>
- Declare a string variable to store the input string:
std::string inputString;
- Take user input for the string:
std::cout << "Enter a string: ";
std::getline(std::cin, inputString);
- Declare a character variable to store the splitting character:
char splitChar;
- Take user input for the splitting character:
std::cout << "Enter the splitting character: ";
std::cin >> splitChar;
- Declare a vector of strings to store the splitted substrings:
std::vector<std::string> substrings;
- Use a
std::stringstream
object to split the string:
std::stringstream ss(inputString);
std::string substring;
- Iterate over the string using
std::getline
and split it on the specified character:
while (std::getline(ss, substring, splitChar)) {
substrings.push_back(substring);
}
- Print the splitted substrings:
std::cout << "Splitted substrings:" << std::endl;
for (const auto& str : substrings) {
std::cout << str << std::endl;
}
That's it! The above steps demonstrate how to split a string on a character in C++. Let me know if you need further assistance!