Use std string

Source: Internet
Author: User

Use string to replace the char * array, use the sort Sorting Algorithm to sort, and use the unique function to return and return duplicates.
1. Define
String s1 = "hello ";
String s2 = "world ";
String s3 = s1 + "," + s2 + "! \ N ";
2. append
S1 + = ", shanshan \ n ";
3. Compare
If (s1 = s2)
.....
Else if (s1 = "hello ")
.....
4. string contains many operators, including +, + =, <, =, [], <,>, and so on. These operators are convenient for string operations.

# Include <string>
# Include <iostream>
Using namespace std;
Int main (){
String strinfo = "Please input your name :";
Cout <strinfo;
Cin> strinfo;
If (strinfo = "winter ")
Cout <"you are winter! "<Endl;
Else if (strinfo! = "Wende ")
Cout <"you are not wende! "<Endl;
Else if (strinfo <"winter ")
Cout <"your name shocould be ahead of winter" <endl;
Else
Cout <"your name shocould be after of winter" <endl;
Strinfo + = ", Welcome to China! ";
Cout <strinfo <endl;
Cout <"Your name is:" <endl;
String strtmp = "How are you? "+ Strinfo;
For (int I = 0; I <strtmp. size (); I ++)
Cout <strtmp [I];
Return 0;
} 5. find function
As search is one of the most frequently used functions, string provides a wide range of search functions. The list is as follows: Function Name Description
Find
Rfind Reverse Lookup
Find_first_of finds any character in the substring and returns the first position.
Find_first_not_of searches for any character that does not contain a substring and returns the first position.
Find_last_of finds any character in the substring and returns the last position.
Find_last_not_of searches for any character that does not contain a substring and returns the last position.
The above functions are reloaded four times. The following uses the find_first_of function as an example to describe their parameters. Other functions are the same as their parameters, that is, there are 24 Functions in total:

Size_type find_first_of (const basic_string & s, size_type pos = 0)
Size_type find_first_of (const charT * s, size_type pos, size_type n)
Size_type find_first_of (const charT * s, size_type pos = 0)
Size_type find_first_of (charT c, size_type pos = 0)

All the lookup functions return a size_type type. The return value is generally the position of the string to be found. If not, the return value is string: npos.
In fact, string: npos indicates-1. -1 is returned if it is not found. Example:
# Include <string>
# Include <iostream>
Using namespace std;
Int main (){
String strinfo = "// * --- Hello Word !...... ------";
String strset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
Int first = strinfo. find_first_of (strset );
If (first = string: npos ){
Cout <"not find any characters" <endl;
Return-1;
}
Int last = strinfo. find_last_of (strset );
If (last = string: npos ){
Cout <"not find any characters" <endl;
Return-1;
}
Cout <strinfo. substr (first, last-first + 1) <endl; // string. substr is a substring.
Return 0;
}
6. insert, replace, and erase Functions

String only provides the replace function based on the position and interval, rather than replacing another string in the specified string with a string.
Example:
# Include <string>
# Include <iostream>
Using namespace std;
Int main (){
String strinfo = "This is Winter, Winter is a programmer. Do you know Winter? ";
Cout <"Orign string is: \ n" <strinfo <endl;
String_replace (strinfo, "Winter", "wende ");
Cout <"After replace Winter with wende, the string is: \ n" <strinfo <endl;
Return 0;
}

String. erase (pos, srclen); // srclen indicates the deleted length.
String. insert (pos, strdst); // pos is the position, and strdst is the inserted function.
Void string_replace (string & strBig, const string & strsrc, const string & strdst ){
String: size_type pos = 0;
String: size_type srclen = strsrc. size ();
String: size_type dstlen = strdst. size ();
While (pos = strBig. find (strsrc, pos ))! = String: npos ){
StrBig. erase (pos, srclen );
StrBig. insert (pos, strdst );
Pos + = dstlen;
}
}

Link: http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailString
 
7. Cut the string
# Include <sstream>
# Include <string>
# Include <iostream>
Using namespace std;
Int main ()
{
String text = "big | dog | china | sonic | free ";
Stringstream ss (text );
String sub_str;
While (getline (ss, sub_str, '|') // use | to separate the content of test.
Cout <sub_str <endl;

Return 0;
}
The output is as follows:
Big
Dog
China
Sonic
Free

8. constructor and destructor
String s generates an empty string S
String s (str) Copy constructor to generate a Copy of the string Str
String s (str, stridx) refers to the part of the string Str that begins with Stridx and is treated as the initial value of string S.
String s (str, stridx, strlen) refers to the part of Str that begins with Stridx and has a length of strlen, and treats it as the initial value of string S (cstr) use C-String cstr as the initial value of S
String s (num, c) generates a string containing Num (C)
String s (beg, end) uses the characters in the interval [beg, end] as the initial values of s.
S .~ String () destroys all characters and releases the memory.
Note:
Std: string s ('x'); // error
Std: string s (1, 'x'); // OK, create a string that has one charactor 'X'

9. substr (string. substr method)

(1) Parameters
Start: Number -- an integer that indicates the position of the first character used to create a substring in my_str. If start is a negative number, the start position is determined from the end of the string, where-1 indicates the last character.
Length: Number -- Number of characters in the substring to be created. If length is not specified, the substring contains all characters starting from the string and ending with the string.
(2) Return
String -- specifies the substring of a String.
(3) Example
The following example creates a new string my_str and returns the second word in the string using substr (). First, use the positive start parameter and then use the negative start parameter:
Var my_str: String = new String ("Hello world ");
Var mySubstring: String = new String ();
MySubstring = my_str.substr (6, 5 );
Trace (mySubstring); // output: world

MySubstring = my_str.substr (-5, 5 );
Trace (mySubstring); // output: world

Toupper, tolower
We all know that C ++'s string does not have toupper. Fortunately, this is not a big problem, because we have STL algorithms:

String s ("heLLo ");
Transform (s. begin (), s. end (), s. begin (), toupper );
Cout <s <endl;
Transform (s. begin (), s. end (), s. begin (), tolower );
Cout <s <endl;

Of course, I know many people want s. to_upper (), but for such a general basic_string, it is indeed impossible to put these proprietary methods in. If you use boost stringalgo, you do not need to read this article.

------------------------------------------------------------------------
Trim
We also know that string does not have trim, but self-reliance is not difficult, it is simpler than toupper:

String s ("hello ");
S. erase (0, s. find_first_not_of ("\ n "));
Cout <s <endl;
S. erase (s. find_last_not_of (''') + 1 );
Cout <s <endl;

Note that both find_first_not_of and find_last_not_of can accept strings. In this case, they can find the absence of all characters in the string, so you can trim multiple characters at a time.

-----------------------------------------------------------------------
Erase
The erase of the string itself is good, but it can only be consecutive characters. What if you want to remove all the characters in a string? Use erase + remove_if of STL. Note that remove_if cannot be used.

String s ("hello, world. say bye ");
S. erase (remove_if (s. begin (), s. end (),
Bind2nd (performance_to <char> (),'''')),
S. end ());

The above section will remove all spaces and get hello, world. saybye.

-----------------------------------------------------------------------
Replace
String itself provides replace, but it is not string-oriented. For example, we need to make a small combination to replace one substr with another:

String s ("hello, world ");
String sub ("ello ,");
S. replace (s. find (sub), sub. size (), "appy ");
Cout <s <endl;

Output is happy world. Note that the original substr is not necessarily the same length as the replaced substr.

-----------------------------------------------------------------------
Startwith, endwith
These two methods are very common, but if you look at the string interface carefully, you will find that there is no need to specifically provide these two methods, and the existing interfaces can do well:

String s ("hello, world ");
String head ("hello ");
String tail ("ld ");
Bool startwith = s. compare (0, head. size (), head) = 0;
Cout <boolalpha <startwith <endl;
Bool endwith = s. compare (s. size ()-tail. size (), tail. size (), tail) = 0;
Cout <boolalpha <endwith <endl;

Of course, it's not as convenient as s. startwith ("hello.

------------------------------------------------------------------------
Toint, todouble, tobool...
This is also an old saying. Both the C method and the C ++ method can have their own characteristics:

String s ("123 ");
Int I = atoi (s. c_str ());
Cout <I <endl;

Int ii;
Stringstream (s)> ii;
Cout <ii <endl;

String sd ("12.3 ");
Double d = atof (sd. c_str ());
Cout <d <endl;

Double dd;
Stringstream (sd)> dd;
Cout <dd <endl;

String sb ("true ");
Bool B;
Stringstream (sb)> boolalpha> B;
Cout <boolalpha <B <endl;

The C method is very concise, and the assignment and conversion are completed in one sentence, while the C ++ method is very common.

------------------------------------------------------------------------
Split
This is a headache. What we hope most is the s. split (vect, '','') interface ,'',''). It is difficult to use the STL algorithm. We can start with a simple one. If the separator is space, tab, and press enter, then this is enough:

String s ("hello world, bye .");
Vector <string> vect;
Vect. assign (
Istream_iterator <string> (stringstream (s )),
Istream_iterator <string> ()
);

However, note that if s is large, it will be more efficient, because stringstream will copy a string for its own use.

------------------------------------------------------------------------
Concat
How to connect all strings in a container containing strings? Hope you don't say it's a hand code loop. Isn't it better?

Vector <string> vect;
Vect. push_back ("hello ");
Vect. push_back (",");
Vect. push_back ("world ");

Cout <accumulate (vect. begin (), vect. end (), string (""));

However, there is room for optimization in terms of efficiency.

-------------------------------------------------------------------------

Reverse
In fact, I suspect someone really needs to reverse a string, but it is really easy to do this:

Std: reverse (s. begin (), s. end ());

The above is the method of in-situ inversion. If you need to reverse to another string, it is as simple:

S1.assign (s. rbegin (), s. rend ());

The efficiency is also quite satisfactory.

-------------------------------------------------------------------------

Parse file extension
Multiple words:

Std: string filename ("hello.exe ");

Std: string: size_type pos = filename. rfind (''.'');
Std: string ext = filename. substr (pos = std: string: npos? Filename. length (): pos + 1 );

But what if two rows are merged into one row? Or not:

Std: string ext = filename. substr (filename. rfind (''.'') = std: string: npos? Filename. length (): filename. rfind (''.'') + 1 );

I know that rfind has been executed twice. But first, you can want the compiler to optimize it. Second, the extension is generally very short. Even if you execute it once more, the difference should be quite small.

Conflict between GBK Chinese encoding and std: string
Recently, I wrote an interface for splitting strings by separator,
Void PickUp (std: string & strDes, std: vector <std: string>

& VecData, const std: string sign = ";")
{
Std: string: size_type fpos = 0, bpos = 0;
Std: string strTemp;
While (bpos! = Std: string: npos & strDes. size ())
{
Bpos = strDes. find (sign, fpos );
StrTemp = strDes. substr (fpos, bpos-fpos );
VecData. push_back (strTemp );
Fpos = bpos + 1;
}
}
It was easy to use at first, but there was a new requirement and the interface was used, but the separator was no longer the default ";", but replaced with the underscore "_". The problem arises: for example, the following code:
Int main () www.2cto.com
{
Std: string strDes ("turn on _ ");
Std: vector <std: string> vecTemp;
PickUp (strDes, vecTemp ,"_");
System ("pause ");
Return 0;
}
You may not see any problem, but the result is incorrect. After carefully tracking the breakpoint and checking relevant information online, you can finally understand the cause.
Std: The find function of string is compared by single-byte search, while GBK uses dual-byte representation. The overall encoding range is 0x8140-FEFE. The first byte is between 0x81-FE, And the last byte is between 0x40-FE.
For example, the memory size of the opening text is e9 5f, the memory size of the opening text is c5 5f, and the memory size of the underline "_" is 5f, that is to say, the last byte of the opening character is the same as that of the underline ascii "_", but the find of std: string cannot be searched by a single byte, therefore, the result is that the size () of vecTemp is changed to 4, which includes two empty strings instead of expected result 2. The problem was not found before because of the semicolon separator ";", the ascii code of ";" is less than 0x40.
So the solution to this problem is that the separator should be less than 0x40, that is, the ascii code is less than 64. You need to check the separators smaller than 64.
Or you can write a single byte to compare the find algorithm .....

Boost: tokenizer is good

Author: zhongguoren666

 

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.