C + + split string (similar to Boost::split)

Source: Internet
Author: User

Because C + + string does not have the split function, so the string division of words must be written by themselves, it is equivalent to implement a split function it!

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

1#include <iostream>2#include <vector>3#include <string>4#include <sstream>5 using namespacestd;6 7 intMain ()8 {9     stringwords;Tenvector<string>results; OneGetline (cin, words);
A Istringstream SS (words); - while(!ss.eof ()) - { the stringWord; -Getline (SS, Word,','); - Results.push_back (word); - } + for(auto Item:results) - { +cout << Item <<" "; A } at}

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

1#include <iostream>2#include <vector>3#include <string>4#include <sstream>5 using namespacestd;6 7vector<Char> is_any_of (stringstr)8 {9vector<Char>Res;Ten      for(auto S:str) One Res.push_back (s); A     returnRes; - } -  the voidSplit (vector<string>& result,stringSTR, vector<Char>delimiters) - { - result.clear (); -Auto start =0; +      while(Start <str.size ()) -     { +         //split based on multiple separators AAuto Itres = Str.find (delimiters[0], start); at          for(inti =1; I < delimiters.size (); ++i) -         { -Auto it =Str.find (delimiters[i],start); -             if(It <itres) -Itres =it; -         } in         if(Itres = =string:: NPOs) -         { toResult.push_back (Str.substr (Start, str.size ()-start)); +              Break; -         } theResult.push_back (Str.substr (Start, Itres-start)); *Start =itres; $++start;Panax Notoginseng     } - } the  + intMain () A { the     stringwords; +vector<string>result; - getline (CIN, words); $Split (result, words, is_any_of (", .?!")); $      for(auto Item:result) -     { -cout << Item <<' '; the     } -}

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

C + + split string (similar to Boost::split)

Related Article

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.