21xrx.com
2024-06-02 23:17:04 Sunday
登录
文章检索 我的文章 写文章
C++字符串函数find的用法和示例
2023-07-01 09:36:57 深夜i     --     --
C++ 字符串函数 find 用法 示例

C++是一种高级编程语言,它提供了丰富的字符串函数来满足程序员们的需求。其中一个常用的函数就是find函数。

find函数是C++ STL中的一个字符串函数,用于查找字符串中第一个匹配子字符串的位置。它的语法如下:

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

其中,string是字符串数据类型,size_type是布尔值(0或1)的大小。str是要查找的子字符串,pos是查找的起始位置。

以下是一个使用find函数的示例:

#include

#include

using namespace std;

int main()

{

  string str("hello, world");

  string substr("world");

  size_t pos = str.find(substr);

  if (pos != string::npos) {

    cout << "Found \"" << substr << "\" at position " << pos << endl;

  } else

    cout << "Not found." << endl;

  return 0;

}

在这个示例中,我们声明了两个字符串变量,str和substr。我们要在str中查找substr的位置。使用find函数,它返回了substr在str中的位置,我们把它存储在pos变量中,如果pos不等于string::npos(表示没找到),我们就输出找到的位置。如果pos等于npos,我们就输出“没找到”。

上述示例代码的输出结果如下:

Found "world" at position 7

总结:

使用find函数可以查找字符串中第一个匹配子字符串的位置。它的语法如下:

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

其中,string是字符串数据类型,size_type是布尔值(0或1)的大小。str是要查找的子字符串,pos是查找的起始位置。

使用例子:

string str("hello, world");

  string substr("world");

  size_t pos = str.find(substr);

  if (pos != string::npos) {

    cout << "Found \"" << substr << "\" at position " << pos << endl;

  } else

    cout << "Not found." << endl;

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复