欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[Cpp primer] Library string Type

程序员文章站 2024-02-29 19:23:28
...

In order to use string type, we need to include the following code

#include<string>
using std::string;

  

1. Defining and initializing strings

string s1; //Default initialization; s1 is the empty string
string 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 null
string 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;
is >> 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 together
It won't add a whitespace automatically.
s1 = "666", s2 = "777"
s3 = s1+s2 = "666777"
*/
string s1 = "mdzz";
s1 = s1 + "haha";  //1
s1 = "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<cctype>
//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 digit
isalpha(c); //True: c is a letter
iscntrl(c); //True: c is a control character
isdigit(c); //True: c is a digit
isgraph(c); //True: c is not a space but is printable
islower(c); //True: c is a lowercase letter
isupper(c);
isprint(c); //True: c is a printable character
ispunct(c); //True: c is a punctuation character
isspace(c); //True: c is a whitespace
isxdigit(c); //True: c is a hexadecimal digit
tolower(c);
toupper(c);