C + + How to split string sample code _c language

Source: Internet
Author: User

Not much to say, directly on the code

If you need to split the word according to a single character, read it directly with Getline, very simple

 #include <iostream>
 #include <vector>
 #include <string>
 #include <sstream>
 using namespace std;
 
 int main ()
 {
   string words;
   vector<string> results;
   Getline (cin, words);
   Istringstream SS (words);
   while (!ss.eof ())
   {
     string word;
     Getline (SS, Word, ', ');
     Results.push_back (word);
   for (auto Item:results)
   {
     cout << item << "";
   }
 }

If it is a variety of character segmentation, for example,.! And so on, you need to write a function similar to split:

 #include <iostream> #include <vector> #include <string> #include <sstream> using namespace s
 
 td
   vector<char> is_any_of (String str) {vector<char> res;
   for (auto S:str) res.push_back (s);
 return res;
   } void Split (vector<string>& result, string str, vector<char> delimiters) {result.clear ();
   Auto start = 0;
     while (Start < Str.size ()) {//split auto Itres = Str.find (Delimiters[0], start) according to multiple delimiters;
       for (int i = 1; i < delimiters.size (); ++i) {Auto it = Str.find (Delimiters[i],start);
     if (it < itres) Itres = it;
       } if (itres = = String::npos) {result.push_back (Str.substr (Start, str.size ()-start);
     Break
     } result.push_back (Str.substr (Start, Itres-start));
     start = Itres;
   ++start;
   int main () {string words;
   vector<string> result;
   Getline (cin, words); Split (result, words, is_any_of (",.?!"));
   for (auto Item:result) {cout << item << '; }
 }

For example: Enter Hello world! Welcome to my Blog,thank you!

The above is C + + how to split string sample code of the entire content, we have learned? I hope this article is helpful to you when you use C + +.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.