21xrx.com
2024-09-20 00:48:49 Friday
登录
文章检索 我的文章 写文章
如何在C++中查找字符串
2023-07-05 05:56:43 深夜i     --     --
C++ 查找字符串 字符串搜索 std::string find()函数

在C++中,如果需要查找字符串中是否包含某个特定的字符或字符串,可以使用库函数和自定义函数两种方式实现。

1. 使用库函数

在C++中,可以使用 头文件中的find函数来查找字符串中是否包含特定的字符或字符串。

查找字符:


string str = "hello world";

char c = 'l';

int pos = str.find(c); // 返回第一个匹配字符的下标,从0开始计数

if (pos != string::npos)

  cout << "找到字符'" << c << "'在第" << pos << "个位置" << endl;

else

  cout << "未找到字符'" << c << "'" << endl;

查找字符串:


string str = "hello world";

string target = "world";

int pos = str.find(target); // 返回第一个匹配字符串的下标,从0开始计数

if (pos != string::npos)

  cout << "找到字符串'" << target << "'在第" << pos << "个位置" << endl;

else

  cout << "未找到字符串'" << target << "'" << endl;

2. 自定义函数

除了使用库函数外,还可以自定义函数来实现字符串的查找。

查找字符:


bool findChar(string s, char c) {

  for (int i = 0; i < s.length(); i++) {

    if (s[i] == c)

      return true;

    

  }

  return false;

}

string str = "hello world";

char c = 'l';

if (findChar(str, c))

  cout << "找到字符'" << c << "'" << endl;

else

  cout << "未找到字符'" << c << "'" << endl;

查找字符串:


bool findString(string s, string target) {

  int len = target.length();

  for (int i = 0; i <= s.length() - len; i++) {

    if (s.substr(i, len) == target)

      return true;

    

  }

  return false;

}

string str = "hello world";

string target = "world";

if (findString(str, target))

  cout << "找到字符串'" << target << "'" << endl;

else

  cout << "未找到字符串'" << target << "'" << endl;

通过上面的两种方式可以轻松实现在C++中查找字符串的操作。

  
  

评论区

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