In C++, the `substr` function is used to extract a substring of a string. It has two common uses:
1. `substr(pos, len)`: Extract a substring of length `len` starting from position `pos`.
- `pos`: Specifies the starting position of the extracted substring, starting from 0.
- `len`: Specifies the length of the extracted substring. If `len` is not specified, all characters from `pos` to the end of the string are extracted by default.
2. `substr(pos)`: Extract the substring starting from position `pos` to the end.
The following is sample code using the `substr` function:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 提取从位置 7 开始的子串
std::string sub1 = str.substr(7);
std::cout << "sub1: " << sub1 << std::endl; // 输出 "World!"
// 提取从位置 7 开始的长度为 5 的子串
std::string sub2 = str.substr(7, 5);
std::cout << "sub2: " << sub2 << std::endl; // 输出 "World"
return 0;
}
In the above example, we used the `substr` function of string to extract the substring at the specified position and print the result.
It should be noted that the `substr` function in C++ returns a new `std::string` object, not a reference or pointer to the original string.
If you want to practice a question, please click here