21xrx.com
2025-03-23 18:39:32 Sunday
文章检索 我的文章 写文章
C++字符串查找函数的源代码
2023-06-22 01:59:42 深夜i     13     0
C++ 字符串 查找函数 源代码

C++字符串查找函数的源代码可以通过多种方式实现,但是其中比较常用的方法是使用循环和条件语句来实现字符串的查找操作。

下面是一个简单的示例代码,它使用了C++标准库中的string类和find()函数来执行字符串查找操作。

#include <iostream>
using namespace std;
int main()
{
  string str = "This is a sample string";
  string search_str = "sample";
  size_t found = str.find(search_str);
  if (found != string::npos)
   cout << "The word 'sample' is found at position: " << found << endl;
  else
   cout << "The word 'sample' is not found." << endl;
  return 0;
}

在上面的代码中,首先定义了一个字符串变量str,它包含了要被查找的字符串。其次,定义了字符串变量search_str,它表示要查找的字符串。

然后,使用string类中的find()函数来查找字符串。如果找到了,该函数将返回匹配的位置,否则将返回string::npos,表示查找失败。

最后,根据find()函数的返回值来打印查找结果,如果找到了,输出匹配的位置,否则输出查找失败的信息。

需要注意的是,find()函数返回的位置是从0开始的,而不是从1开始。此外, find()函数会从字符串的开头开始查找,如果需要从字符串的某个位置开始查找,可以使用find_first_of()或find_last_of()函数。

  
  

评论区