21xrx.com
2024-09-20 00:04:48 Friday
登录
文章检索 我的文章 写文章
C++:判断字符串是否包含另一个字符串
2023-06-29 03:40:41 深夜i     --     --
C++ 判断 字符串 包含 另一个字符串

在C++中,要判断一个字符串是否包含另一个字符串,可以使用string类提供的find()函数。该函数返回第一次在当前字符串中找到要查找的子字符串的位置(从0开始),如果未找到则返回string::npos。

下面是一个示例程序:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str1 = "hello world";

  string str2 = "world";

  size_t found = str1.find(str2);

  if (found != string::npos)

  

    cout << "str1 contains str2 at position " << found << endl;

  

  else

  

    cout << "str1 does not contain str2" << endl;

  

  return 0;

}

在这个示例程序中,我们定义了两个字符串str1和str2。我们想知道str1是否包含str2。我们使用find()函数在str1中查找str2,并将结果存储在变量found中。如果找到,我们输出找到的位置;否则,我们输出一条消息指出str1不包含str2。

在C++中,我们可以使用这种简单而有效的方法来判断一个字符串是否包含另一个字符串。此外,string类还提供了许多其他有用的函数,如substr()、compare()等,可以在需要的时候使用。

  
  

评论区

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