c++substr用法
时间: 2024-05-18 15:09:41 浏览: 12
C++中的substr函数用于截取字符串的一部分。它的语法格式为:
```c++
string substr (size_t pos, size_t len) const;
```
其中,pos表示要截取的起始位置,len表示要截取的长度。
举个例子,如果有一个字符串str,我们想要截取从第三个字符开始,长度为5的子串,可以这样写:
```c++
string str = "Hello World";
string subStr = str.substr(2, 5);
```
这样就可以得到子串"llo W"。
注意,substr返回的是一个新的字符串,原字符串不会受到影响。如果省略len参数,则从pos开始截取到字符串末尾。
相关问题
c++ substr用法
C++中的substr()函数用于截取字符串的一部分。它的语法如下:
```c++
string substr (size_t pos, size_t len) const;
```
其中,pos表示要截取的子字符串的起始位置,len表示要截取的子字符串的长度。注意,pos从0开始计数,len的默认值为string::npos,表示截取从pos开始到字符串结尾的全部字符。
以下是一个使用substr()函数的示例:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "Hello, world!";
string sub = s.substr(0, 5);
cout << sub << endl;
return 0;
}
```
以上代码将输出"Hello",因为它截取了字符串s的前5个字符。
c++substr函数用法
C++中的`substr`函数是用于获取一个字符串的子串。它的用法如下```cpp
string substr (size_t pos, size_t len) const;
```
其中,`pos`表示子串的起始位置,`len`表示子串的长度。如果`len`参数被省略,则默认取到字符串结尾。返回值是一个新的`string`对象,包含了原字符串中指定位置和长度的子串。
示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string subStr = str.substr(6, 5);
cout << subStr << endl; // 输出 "world"
return 0;
}
```
在上面的例子中,我们定义了一个字符串`str`,然后使用`substr`函数获取了从位置6开始的长度为5的子串,即"world"。