What is the purpose of the string substr function in C+…
The function string.substr() in C++ is used to extract a substring from a string. It takes two parameters: the starting position and the length of the substring. This function will return a new string containing the extracted substring from the original string.
Here is the syntax for the string.substr() function:
string substr (size_t pos, size_t len) const;
- pos: Starting position for extracting a substring. If pos exceeds the length of the string, the function will return an empty string.
- len: the length of the extracted sub-string. If not specified, the string will be extracted from the starting position to the end.
Here is an example of using the string.substr() function:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5);
std::cout << sub << std::endl; // 输出 "World"
return 0;
}
In the example above, str.substr(7, 5) extracts a substring of length 5 starting from index 7, which means it grabs 5 characters starting from position 7, resulting in “World”.