C++ string (string) common operation summary

Table of contents

0. Summary of common functions

1. Define a string

2. Read and write string operations

3. Query string information, index

4. Operations such as splicing and comparison

5. cctype header file (judging character type: upper/lower case letters, punctuation, numbers, etc.)

6. For loop traversal

7. Modify the string operation

8. string search operation

9. Conversion between string, char and numeric values

10. String reverse 

11. Extract string


One character enclosed in single quotes is called a char literal , and zero or more characters enclosed in double quotes form a string literal . The type of string literal is actually an array of constant characters , and the compiler adds a null character ('\0') after each string, so the actual length of the string is 1 more than its content.

For example, the literal value 'A' represents a single character A, and the string "A" represents a character array containing two characters, which are the letter A and the null character.

0. Summary of common functions

s.insert(pos, args)   Insert the characters specified by args before pos
s.erase(pos, len)   Deletes len characters starting at pos. If len is omitted, all characters beginning with pos are deleted. Returns a reference to s.
s.assign(args)   Replaces the characters in s with the characters specified by args. Returns a reference to s.
s.append(args)   Append args to s. Returns a reference to s. args must be a double-quoted string
s.replace(range, args)  Replace characters in range in s with the characters specified by args
s.find(args)  find the first occurrence of args in s
s.rfind(args)  find the last occurrence of args in s
to_string(val) Converts the numeric value val to a string and returns it. val can be any arithmetic type (int, float, etc.)
stoi (s)/ atoi (c) String/Char to integer and back
substance (s) / atof (s) String/char conversion to float and back
s.substr(pos, n) Starting from index pos, extract consecutive n characters, including the character at position pos
reverse(s2.begin(), s2.end()) Reverse the string s2 defined by string (add the header file <algorithm> )

1. Define a string

To declare and initialize a string using the standard library type string, the header file string needs to be included . It can be initialized as follows:

    string s1;    // 初始化一个空字符串
    string s2 = s1;   // 初始化s2,并用s1初始化
    string s3(s2);    // 作用同上
    string s4 = "hello world";   // 用 "hello world" 初始化 s4,除了最后的空字符外其他都拷贝到s4中
    string s5("hello world");    // 作用同上
    string s6(6,'a');  // 初始化s6为:aaaaaa
    string s7(s6, 3);  // s7 是从 s6 的下标 3 开始的字符拷贝
    string s8(s6, pos, len);  // s7 是从 s6 的下标 pos 开始的 len 个字符的拷贝

Using = is copy initialization, and using () is direct initialization. Both are acceptable when there is only one initial value. When there are multiple initial values, direct initialization is generally used, such as the last form above.

2. Read and write string operations

Encountering a space or enter key while typing will stop. But it should be noted that the input execution will end only when the Enter key is pressed, and the input can be continued after the space is pressed, but the string entered before the first space is finally saved in the string (the blank at the beginning Except, the program will automatically ignore the blank at the beginning), and the space operation can be used to initialize multiple strings at the same time, as in the following example

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
    string s1, s2, s3;    // 初始化一个空字符串
    // 单字符串输入,读入字符串,遇到空格或回车停止
    cin >> s1;  
    // 多字符串的输入,遇到空格代表当前字符串赋值完成,转到下个字符串赋值,回车停止
    cin >> s2 >> s3;  
    // 输出字符串 
    cout << s1 << endl; 
    cout << s2 << endl;
    cout << s3 << endl;   
    return 0;
}
// 运行结果 //
  abc def hig
abc
def
hig

If you want to keep spaces in the final read string, you can use the getline function, examples are as follows:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string s1 ;    // 初始化一个空字符串
    getline(cin , s1); 
    cout << s1 << endl;  // 输出
    return 0;
}
// 结果输出 //
abc def hi
abc def hi

3. Query string information, index

You can use empty size/length to query the status and length of the string, and you can use the subscript operation to extract the characters in the string. 

#include <iostream>
#include <string>
using namespace std;
int main(void)
{
    string s1 = "abc";    // 初始化一个字符串
    cout << s1.empty() << endl;  // s 为空返回 true,否则返回 false
    cout << s1.size() << endl;   // 返回 s 中字符个数,不包含空字符
    cout << s1.length() << endl;   // 作用同上
    cout << s1[1] << endl;  // 字符串本质是字符数组
    cout << s1[3] << endl;  // 空字符还是存在的
    return 0;
}
// 运行结果 //
0
3
3
b

4. Operations such as splicing and comparison

s1+s2          // 返回 s1 和 s2 拼接后的结果。加号两边至少有一个 string 对象,不能都是字面值
s1 == s2       // 如果 s1 和 s2 中的元素完全相等则它们相等,区分大小写
s1 != s2
<, <=, >, >=   // 利用字符的字典序进行比较,区分大小写

5. cctype header file (judging character type: upper/lower case letters, punctuation, numbers, etc.)

The cctype header file contains library functions for character operations in string, as follows:

isalnum(c)  // 当是字母或数字时为真
isalpha(c)  // 当是字母时为真
isdigit(c)  // 当是数字是为真
islower(c)  // 当是小写字母时为真
isupper(c)  // 当是大写字母时为真
isspace(c)  // 当是空白(空格、回车、换行、制表符等)时为真
isxdigit(c) // 当是16进制数字是为真
ispunct(c)  // 当是标点符号时为真(即c不是 控制字符、数字、字母、可打印空白 中的一种)
isprint(c)  // 当时可打印字符时为真(即c是空格或具有可见形式)
isgraph(c)  // 当不是空格但可打印时为真
iscntrl(c)  // 当是控制字符时为真
tolower(c)  // 若c是大写字母,转换为小写输出,否则原样输出
toupper(c)  // 类似上面的

6. For loop traversal

You can use the c++11 standard for (declaration: expression)  form to loop through, the example is as follows:

( If you want to change the value in the string object, you must define the loop variable as a reference type )

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(void)
{
    string s1 = "nice to meet you~";    // 初始化一个空字符串
    // 如果想要改变 string 对象中的值,必须把循环变量定义为引用类型。引用只是个别名,相当于对原始数据进行操作
    for(auto &c : s1)  
        c = toupper(c); 
    cout << s1 << endl; // 输出
    return 0;
}
// 运行结果 //
NICE TO MEET YOU~

7. Modify the string operation

Inserts the characters specified by args before pos. pos is a subscript or iterator. The version that accepts a subscript returns a reference to s; the version that accepts an iterator returns an iterator to the first inserted character 

s.insert(pos, args)  
// 在 s 的位置 0 之前插入 s2 的拷贝
s.insert(0, s2)  

Deletes len characters starting at pos. If len is omitted, all characters beginning with pos are deleted. Returns a reference to s.

s.erase(pos, len)  

Replaces the characters in s with the characters specified by args. Returns a reference to s.

s.assign(args)  

Append args to s. Returns a reference to s. args cannot be a single quote character, if it is a single character it must be expressed in double quotes. For example, it can be s.append( " A " ) but not s.append( ' A ' )    

s.append(args)  

Replaces the characters in range in s with the characters specified by args. range is either a subscript or length, or a pair of iterators pointing to s. Returns a reference to s.

s.replace(range, args) 
// 从位置 3 开始,删除 6 个字符,并插入 "aaa".删除插入的字符数量不必相等
s.replace(3, 6, "aaa")  

8. string search operation

The search operation returns the subscript where the specified character occurs, or npos if not found 

s.find(args)  // 查找 s 中 args 第一次出现的位置
s.rfind(args)  // 查找 s 中 args 最后一次出现的位置

Find the earliest/latest occurrence of any of the characters in args in s

s.find_first_of(args)  // 在 s 中查找 args 中任何一个字符最早出现的位置
s.find_last_of(args)  // 在 s 中查找 args 中任何一个字符最晚出现的位置
例如:
string s1 = "nice to meet you~"; 
cout << s1.find_first_of("mey") << endl; // 输出结果为 3,'e' 出现的最早

Find the position of the first/last character in s not in args

s.find_first_not_of(args)  // 查找 s 中 第一个不在 args 中的字符的位置
s.find_last_not_of(args)  // 查找 s 中 最后一个不在 args 中的字符的位置
例如:
string s1 = "nice to meet you~";  
cout << s1.find_first_not_of("nop") << endl; // 输出结果为 1 ,'i' 不在 "nop" 里

9. Conversion between string, char and numeric values

1. Convert the value val to string. val can be any arithmetic type (int, float, etc.).

string s = to_string(val)

2. Convert to integer and return . The return types are int, long, unsigned long, long long, unsigned long long. b represents the base number used for conversion, the default is 10, that is, the string is converted as a number in base, and the final result is still in decimal representation. p is a size_t pointer, used to save the subscript of the first non-numeric character in s, the default is 0, that is, the function does not save the subscript, and this parameter can also be a null pointer, which is not used in this case.

stoi(s)
// 函数原型 int stoi (const string&  str, size_t* idx = 0, int base = 10);
stoi(s, p, b)
stol(s, p, b)
stoul(s, p, b)
stoll(s, p, b)
stoull(s, p, b)
// 例如
string s1 = "11";    // 初始化一个空字符串
int a1 = stoi(s1);
cout << a1 << endl; // 输出 11
int a2 = stoi(s1, nullptr, 8);
cout << a2 << endl; // 输出 9
int a3 = stoi(s1, nullptr, 2);
cout << a3 << endl; // 输出 3

3. Convert to a floating point number and return. The return types are float, double, long double respectively. p is a size_t pointer, used to save the subscript of the first non-numeric character in s, the default is 0, that is, the function does not save the subscript, and this parameter can also be a null pointer, which is not used in this case.

stof(s)
stof(s, p)
stod(s, p)
stold(s, p)

4. Convert the value of char type. Note that the parameter passed in is a pointer type, that is, the address of the character is to be taken

atoi(c)
// 函数原型 int atoi(const char *_Str)
atol(c)
atoll(c)
atof(c)

10. String reverse 

Use the reverse() method in the <algorithm> header file:

    string s2 = "12345";    // 初始化一个字符串
    reverse(s2.begin(), s2.end()); // 反转 string 定义的字符串 s2 
    cout << s2 << endl; // 输出 54321

11. Extract string

 Use  string ss = s.substr(pos, n) . Starting from index pos, extract consecutive n characters, including the character at position pos. Function prototype:

inline std::__cxx11::string std::__cxx11::string::substr(std::size_t __pos, std::size_t __n) const

Guess you like

Origin blog.csdn.net/Flag_ing/article/details/123361432