How to Split a String in C++?
- Time:2020-09-09 13:16:32
- Class:Weblog
- Read:28
In C++, there is no inbuilt split method for string. It is very useful to split a string into a vector of string. We can use the following string split method to split a string into a vector or string using the stringstream class.
1 2 3 4 5 6 7 8 9 | vector<string> split(const string& text) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp,' ')) { stk.push_back(tmp); } return stk; } |
vector<string> split(const string& text) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp,' ')) { stk.push_back(tmp); } return stk; }
Example usage:
1 2 3 4 5 6 7 8 | int main() { string str = "This is me"; vector<string> words = split(str); // words = ["This", "is", "me"]; for (const auto &n: words) { cout << n << endl; } } |
int main() { string str = "This is me"; vector<string> words = split(str); // words = ["This", "is", "me"]; for (const auto &n: words) { cout << n << endl; } }
And of course, you can easily add the support for custom delimiter such as split a string by comma or colon (IP addresses):
1 2 3 4 5 6 7 8 9 | vector<string> split(const string& text, char delimiter) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp, delimiter)) { stk.push_back(tmp); } return stk; } |
vector<string> split(const string& text, char delimiter) { string tmp; vector<string> stk; stringstream ss(text); while(getline(ss,tmp, delimiter)) { stk.push_back(tmp); } return stk; }
Let’s hope that a string split function will be added to the string class in future C++ releases!
–EOF (The Ultimate Computing & Technology Blog) —
Recommend:What You Need if You Want to Be a Freelancer
Best Ways to Maximize the Speed & Performance of Your Word
Essential Google Chrome Extensions For SEO
10 Inspiring Home Improvement Blogs
How to Get More Comments For Your Blog Posts
Gmail Hacks and Tips for Bloggers
6 Handy Tools That Can Convert Your Website Into An App
7 Common Email List Building Mistakes
How to Do Email Marketing in 2020: A Beginner’s Guide
5 Music Blogs That Are Rocking It And How To Get Your Own Band F
- Comment list
-
- Comment add