子字符串是字符串的一部分。在C ++中获得子字符串的函数是substr()
。该函数包含两个参数:pos和len。pos参数指定子字符串的开始位置,len表示子字符串中的字符数。
给出了在C ++中获取子字符串的程序,如下所示-
#include <iostream> #include <string.h> using namespace std; int main() { string str1 = "Apples are red"; string str2 = str1.substr(11, 3); string str3 = str1.substr(0, 6); cout << "Substring starting at position 11 and length 3 is: " << str2 <<endl; cout << "Substring starting at position 0 and length 6 is: " << str3; return 0; }
输出结果
上面程序的输出如下-
Substring starting at position 11 and length 3 is: red Substring starting at position 0 and length 6 is: Apples
在上面的程序中,str1被声明为“苹果是红色的”。然后,str2存储从位置11开始且长度为3的str1的子字符串。此外,str3存储从位置0开始并长度为6的str1的子字符串。这在下面给出-
string str1 = "Apples are red"; string str2 = str1.substr(11, 3); string str3 = str1.substr(0, 6);
显示str2和str3的内容。为此的代码片段如下-
cout << "Substring starting at position 11 and length 3 is: " << str2 <<endl; cout << "Substring starting at position 0 and length 6 is: " << str3;