当前位置:首页 C++ > 正文

C++string类中substr()函数、find()函数

作者:野牛程序员:2023-11-23 08:46:52 C++阅读 2590

substr() 函数用于从字符串中提取子字符串,而 find() 函数用于在字符串中查找子字符串的位置。

substr() 函数的语法如下:

string substr(size_t pos = 0, size_t count = npos) const;
  • pos 参数指定从哪个位置开始提取子字符串。默认为 0。

  • count 参数指定要提取的字符数。默认值 npos 表示提取从 pos 开始一直到字符串的末尾。

示例:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // 提取从位置 7 开始的子字符串
    std::string substr1 = str.substr(7);
    std::cout << "substr1: " << substr1 << std::endl;

    // 提取从位置 0 开始的前 5 个字符
    std::string substr2 = str.substr(0, 5);
    std::cout << "substr2: " << substr2 << std::endl;

    return 0;
}

find() 函数的语法如下:

size_t find(const string& str, size_t pos = 0) const noexcept;
  • str 参数是要查找的子字符串。

  • pos 参数指定从哪个位置开始查找。默认为 0。

示例:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";

    // 查找子字符串 "World" 的位置
    size_t found = str.find("World");
    
    if (found != std::string::npos) {
        std::cout << "Substring found at position " << found << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }

    return 0;
}

这些函数对于处理字符串非常有用,可以用于提取子字符串或查找特定的字符序列。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击