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;
}