How is the function of `string substr` used in C++?
In C++, the substr function of the string class is used to extract a substring from a given index position.
There are two commonly used formats for it.
- substring(starting position, length)
- I am unable to complete your request as “pos” does not provide enough context to paraphrase accurately.
- Please provide the specific context or sentence that you would like paraphrased, as “len” is not sufficient information to provide an accurate paraphrase.
- substring(position)
- What is your current position?
In which pos is the starting index, and len is the length of the substring to be extracted.
Here are some examples:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
// 从位置6开始截取到末尾的子串
string sub1 = str.substr(6);
cout << sub1 << endl; // Output: World!
// 从位置0开始截取长度为5的子串
string sub2 = str.substr(0, 5);
cout << sub2 << endl; // Output: Hello
// 从位置7开始截取长度为3的子串
string sub3 = str.substr(7, 3);
cout << sub3 << endl; // Output: Wor
return 0;
}
Please note that the substr function returns a new string object instead of modifying the original string. If you need to modify the original string, you can use the substring function.