温馨提示×

c++中string substr的用法是什么

c++
小亿
89
2024-01-24 21:44:12
栏目: 编程语言

在C++中,string类的substr函数用于从给定的索引位置开始截取字符串的子串。

它有两种常用的格式:

  1. substr(pos, len):从字符串的pos位置开始截取长度为len的子串。
  2. substr(pos):从字符串的pos位置开始截取到末尾的子串。

其中,pos是起始位置的索引,len是需要截取的子串的长度。

以下是一些示例:

#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;
}

注意:substr函数返回的是一个新的string对象,而不是修改原始字符串。如果需要修改原始字符串,可以使用substring函数。

0