c++中string的substr函数

在 C++ 中,`substr` 函数用于提取字符串的子串。它有两种常用的用法:

1. `substr(pos, len)`: 提取从位置 `pos` 开始的长度为 `len` 的子串。
   - `pos`:指定提取子串的起始位置,位置从 0 开始。
   - `len`:指定提取子串的长度。如果不指定 `len`,则默认提取从 `pos` 到字符串末尾的所有字符。

2. `substr(pos)`: 提取从位置 `pos` 开始到末尾的子串。

以下是使用 `substr` 函数的示例代码:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 提取从位置 7 开始的子串
    std::string sub1 = str.substr(7);
    std::cout << "sub1: " << sub1 << std::endl;  // 输出 "World!"
    
    // 提取从位置 7 开始的长度为 5 的子串
    std::string sub2 = str.substr(7, 5);
    std::cout << "sub2: " << sub2 << std::endl;  // 输出 "World"
    
    return 0;
}

在上面的示例中,我们使用了字符串的 `substr` 函数来提取指定位置的子串,并将结果打印输出。

需要注意的是,C++ 中的 `substr` 函数返回的是一个新的 `std::string` 对象,而不是原始字符串的引用或指针。
 

想练习个题请戳这里

Ancient Prophesy - 洛谷

猜你喜欢

转载自blog.csdn.net/m0_74153798/article/details/131847142