C++字符串截取

C++字符串截取教程

C++ 中,我们需要截取 字符串 或者说获取字符串的子串,可以使用 substr 函数,其中 substr 函数的两个参数都有默认值。

C++字符串substr详解

语法

string substr(int pos = 0, int n = string::npos) const;

参数

参数 描述
pos 要截取的开始的下标。
n 要截取的长度,默认截取到最后。

返回值

返回截取后的字符串。

案例

字符串截取

C++ 截取字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string retStr = str.substr(); cout << "Str = " << str << ", RetStr = " << retStr << endl; }

程序运行后,控制台输出如下:

15_C字符串string截取.png

我们首先,定义了一个字符串 变量 str,接着,我们使用了字符串的 substr 函数实现了截取字符串,substr 函数我们没有传入任何参数,因此,这里使用的全部是默认参数。

即,从第一个字符开始截取,截取到最后,因此,最后返回的字符串还是原来的字符串。

字符串截取

C++ 截取字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string retStr = str.substr(6); cout << "Str = " << str << ", RetStr = " << retStr << endl; }

程序运行后,控制台输出如下:

16_C字符串string截取substr.png

这里,我们使用 substr 函数截取字符串,我们只传入了开始索引,这里传入的是 6,结束参数,我们使用的默认值,即截取到最后。

字符串截取

C++ 截取字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str = "Hello HaiCoder"; string retStr = str.substr(6, 3); cout << "Str = " << str << ", RetStr = " << retStr << endl; }

程序运行后,控制台输出如下:

17_C字符串string截取substr.png

这里,我们使用 substr 函数截取字符串,从第六个字符开始截取,截取三个长度。

C++字符串截取总结

在 C++ 中,我们需要截取字符串或者说获取字符串的子串,可以使用 substr 函数,其中 substr 函数的两个参数都有默认值。