split a string in c++ code example
Example 1: split string on character c++
#include <string>
#include <sstream>
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
Example 2: How to split a string in Java
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0];
String part2 = parts[1];
Example 3: split string in c#
string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');
foreach (var word in words)
{
System.Console.WriteLine($"<{word}>");
}
Example 4: how to split a string in java
public class GFG {
public static void main(String args[])
{
String str = "geekss@for@geekss";
String[] arrOfStr = str.split("@", 2);
for (String a : arrOfStr)
System.out.println(a);
}
}
Example 5: c++ split at character
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
Example 6: split a string based on a delimiter in c++
void tokenize(string &str, char delim, vector<string> &out)
{
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != string::npos)
{
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
int main()
{
string s="a;b;c";
char d=';';
vector<string> a;
tokenize(s,d,a);
for(auto it:a) cout<<it<<" ";
return 0;
}