C ++ uses STL string to implement split, trim, replace

Source: Internet
Author: User

Removes spaces on both sides of the string, truncates and replaces the string with specified characters.

# Include <iostream>
# Include <vector>
Using namespace std;

Namespace strtool
{
String trim (const string & str)
{
String: size_type pos = str. find_first_not_of ('');
If (pos = string: npos)
{
Return str;
}
String: size_type pos2 = str. find_last_not_of ('');
If (pos2! = String: npos)
{
Return str. substr (pos, pos2-pos + 1 );
}
Return str. substr (pos );
}
Int split (const string & str, vector <string> & ret _, string sep = ",")
{
If (str. empty ())
{
Return 0;
}

String tmp;
String: size_type pos_begin = str. find_first_not_of (sep );
String: size_type comma_pos = 0;

While (pos_begin! = String: npos)
{
Comma_pos = str. find (sep, pos_begin );
If (comma_pos! = String: npos)
{
Tmp = str. substr (pos_begin, comma_pos-pos_begin );
Pos_begin = comma_pos + sep. length ();
}
Else
{
Tmp = str. substr (pos_begin );
Pos_begin = comma_pos;
}

If (! Tmp. empty ())
{
Ret _. push_back (tmp );
Tmp. clear ();
}
}
Return 0;
}
String replace (const string & str, const string & src, const string & dest)
{
String ret;

String: size_type pos_begin = 0;
String: size_type pos = str. find (src );
While (pos! = String: npos)
{
Cout <"replacexxx:" <pos_begin <"" <pos <"\ n ";
Ret. append (str. data () + pos_begin, pos-pos_begin );
Ret + = dest;
Pos_begin = pos + 1;
Pos = str. find (src, pos_begin );
}
If (pos_begin <str. length ())
{
Ret. append (str. begin () + pos_begin, str. end ());
}
Return ret;
}

}

Int main (int argc, char * argv [])
{
Cout <strtool: trim ("nihao") <"\ n ";

Vector <string> vt;
Strtool: split (", o h, nice,", vt );
For (size_t I = 0; I <vt. size (); ++ I)
{
Cout <"out:" <vt [I] <"\ n ";
}

String ret = strtool: replace ("xxAxxxAxxAxx", "A", "B ");
Cout <"replace:" <ret <"\ n ";
Return 0;
}

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.