In order to use string type, we need to include the following code
#includeusing std::string;
1. Defining and initializing strings
string s1; //Default initialization; s1 is the empty stringstring s2(s1); //s2 is a copy of s1.string s2 = s1; //Equivalent to s2(s1), s2 is a copy of s1.string s3("value"); //Direct initialization, s3 is a copy of the string literal, not including the nullstring s3 = "value"; //Equivalent to s3("value"), s3 is a copy of the string literal.string s4(n, 'c'); //s4="cccc...ccc", n c
2. Operations on strings
os << s; //Write s onto output stream os. Return os. ex: cout<> s; //Reads whitespace-separeted(if it comes across a whitespace, it stops reading) string from is into s. Rreturn is. ex: cin>>s;getline(is, s); //Reads a line of input from is to s. Return is. is can be 'cin' and other types. //getline(cin, s) This function can read a total line, including whitespace. If it comes across the end-of-line, it stops reading.s.empty();s.size(); //Returns the number of characters in s. If s has whitespace, it still counts. Null character is not included in this size./*size() doesn't return a int type value.However, it returns a string::size_type value.size_type is a companion type of string.It's an unsigned type.We should be aware that we'd better not to mix int with size_type.*/s1 == s2;s1 != s2;>, <, <=, >=//We can use the strategy as a(case-sensitive) dictionary to compare twos strings.s1 + s2;s1 += s2;/*adding two strings togetherIt won't add a whitespace automatically.s1 = "666", s2 = "777"s3 = s1+s2 = "666777"*/string s1 = "mdzz";s1 = s1 + "haha"; //1s1 = "haha" + s1; //2/*String literals are not standard library strings.Hence, string literals can not be the left-hand operand.2 is wrong.1 is ok.*/
3. Dealing with the Characters in a string
#include//Using this header, we can use many functions to deal with the characters in a string.isalnum(c); //True: c is a letter or a digitisalpha(c); //True: c is a letteriscntrl(c); //True: c is a control characterisdigit(c); //True: c is a digitisgraph(c); //True: c is not a space but is printableislower(c); //True: c is a lowercase letterisupper(c);isprint(c); //True: c is a printable characterispunct(c); //True: c is a punctuation characterisspace(c); //True: c is a whitespaceisxdigit(c); //True: c is a hexadecimal digittolower(c);toupper(c);