21xrx.com
2024-09-20 00:11:38 Friday
登录
文章检索 我的文章 写文章
如何判断C++字符串是否包含指定字符或子串?
2023-07-04 09:06:34 深夜i     --     --
C++ 字符串 判断 包含 指定字符 子串

C++是一种广泛应用于计算机科学领域的编程语言,而字符串操作是其中十分重要的一部分。在实际开发中,我们常需要判断一个字符串是否包含指定的字符或子串,下面介绍几种方法来实现这个功能。

1. find函数

在C++中,string类有一个成员函数find,可以用来查找字符串中是否包含指定字符或子串,如果找到则返回对应位置的下标,如果没找到则返回string::npos。以下是示例代码:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "hello world";

  if (str.find('o') != string::npos)

    cout << "包含字符'o'" << endl;

  if (str.find("world") != string::npos)

    cout << "包含子串'world'" << endl;

  return 0;

}

运行结果:


包含字符'o'

包含子串'world'

2.使用STL算法

C++标准库提供了STL算法,其中有一个函数find,可以用来在字符串中查找指定字符或子串。以下是示例代码:


#include <iostream>

#include <string>

#include <algorithm>

using namespace std;

int main()

{

  string str = "hello world";

  if (find(str.begin(), str.end(), 'o') != str.end())

    cout << "包含字符'o'" << endl;

  if (search(str.begin(), str.end(), "world", "world" + 5) != str.end())

    cout << "包含子串'world'" << endl;

  return 0;

}

运行结果:


包含字符'o'

包含子串'world'

3.正则表达式

C++11引入了正则表达式库,可以用来更方便地进行字符串匹配。以下是示例代码:


#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main()

{

  string str = "hello world";

  regex r1("o");

  if (regex_search(str, r1))

    cout << "包含字符'o'" << endl;

  regex r2("world");

  if (regex_search(str, r2))

    cout << "包含子串'world'" << endl;

  return 0;

}

运行结果:


包含字符'o'

包含子串'world'

综上所述,以上三种方法都可以用来判断C++字符串是否包含指定字符或子串,可以根据实际情况选择其中的一种使用。最后需要注意的是,在使用find和STL算法时,如果字符串过长,效率可能会较低。

  
  

评论区

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