What is the usage of the c++ substr function?
In C++, the substr function is used to extract a substring from a string. It is used as follows:
string substr (size_t pos, size_t len) const;
Description of Parameters:
- Start position: the starting position of the substring, indicating from which character of the original string to extract the substring.
- len: The length of the substring, indicating how many characters to extract.
Result:
- Return the substring extracted from the original string.
Example:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string substr = str.substr(7, 5);
std::cout << substr << std::endl; // 输出 "World"
return 0;
}
In the example above, the substr function is used to extract 5 characters starting from the 7th character in the string “Hello, World!”, which is “World”. The extracted substring is then assigned to the substr variable and the result is outputted.