21xrx.com
2025-03-26 13:21:43 Wednesday
文章检索 我的文章 写文章
C++如何在字符串中查找子串
2023-06-25 10:28:55 深夜i     33     0
C++ 字符串 查找 子串

C++是一种广泛使用的编程语言,它可以使用简单而强大的算法来查找字符串中的子串,这对于许多编程任务都是必不可少的。

在C++中查找字符串中的子串主要使用的是内置函数string.find()。该函数的语法如下:

int find(const string& str, int pos = 0) const noexcept;

该函数接受两个参数:需要查找的子串和查找的起始位置(pos)。该函数返回查找到的子串的位置,如果未找到,则返回-1。

以下是一个使用string.find()函数查找子串的示例代码:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string str = "Hello, World!";
  string subStr = "World";
  // Find the sub string in the string
  int pos = str.find(subStr);
  // Check if the sub string is found in the string
  if (pos != -1)
    cout << "Sub string found at position: " << pos << endl;
   else
    cout << "Sub string not found!" << endl;
  
  return 0;
}

上述代码将输出“Sub string found at position: 7”在终端上。

在上述示例中,我们使用了string.find()函数来查找字符串中是否包含某个特定的子串。如果找到了该子串,该函数将返回子串的位置。如果子串未被找到,将返回-1。

总的来说,C++中查找字符串中子串可以通过内置函数string.find()实现。该函数的参数包括需要查找的子串和查找的起始位置。此外,也可以使用其他方法来查找字符串中的子串,但使用string.find()函数可以大大简化编程过程。

  
  

评论区