溫馨提示×

C++ str.find的參數(shù)及使用技巧

c++
小樊
92
2024-08-08 23:11:37
欄目: 編程語言

在C++中,str.find()函數(shù)用于在字符串中查找特定子串的位置。其參數(shù)包括要查找的子串以及可選的起始位置。

語法如下:

size_t find (const string& str, size_t pos = 0) const noexcept;

其中,參數(shù)的含義如下:

  • str: 要查找的子串
  • pos: 查找的起始位置,默認(rèn)為0

使用示例:

#include <iostream>
#include <string>

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

    // 在字符串中查找子串的位置
    size_t found = str.find(sub);
    
    if (found != std::string::npos) {
        std::cout << "子串在字符串中的位置為:" << found << std::endl;
    } else {
        std::cout << "子串未找到" << std::endl;
    }
    
    return 0;
}

在上面的示例中,我們使用find()方法在字符串中查找子串"World"的位置,并輸出結(jié)果。如果子串存在,則返回子串在字符串中的起始位置,否則返回std::string::npos。

0