21xrx.com
2025-03-21 20:25:37 Friday
文章检索 我的文章 写文章
C++字符串查找指定字符
2023-06-28 14:23:08 深夜i     24     0
C++ 字符串 查找 指定字符 字符定位

在C++中,字符串是一种非常常见的数据类型,其由多个字符组成。在实际编程过程中,有时我们需要在字符串中查找指定字符的位置。

C++提供了两种方法来查找字符串中的指定字符。第一种方法使用“for”循环遍历字符串的每个字符,找到指定字符后返回其位置。第二种方法则使用C++标准库提供的string类及其成员函数来实现。

下面分别介绍这两种方法的实现方式:

方法一:循环遍历字符串

使用for循环语句和数组方式来获取字符串中指定字符的位置,操作如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "This is a test string!";
  char ch = 't';
  int len = str.length();
  int pos = -1//标记字符位置,默认为-1
  for (int i = 0; i < len; i++)
  {
    if (str[i] == ch)
    
      pos = i;
      break//找到后直接退出循环
    
  }
  if (pos == -1)
    cout << ch << " not found in the string." << endl;
  else
    cout << ch << " found at position: " << pos << endl;
  return 0;
}

运行以上代码,输出结果如下:

t found at position: 10

方法二:使用string类的成员函数

在C++中,string类提供了find()和rfind()两个成员函数,用来在字符串中查找指定字符,其操作方法如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str = "This is a test string!";
  char ch = 't';
  int pos = -1//标记字符位置,默认为-1
  pos = str.find(ch);
  if (pos == -1)
    cout << ch << " not found in the string." << endl;
  else
    cout << ch << " found at position: " << pos << endl;
  return 0;
}

运行以上代码,输出结果如下:

t found at position: 10

可以看出,以上两个方法都可用于查找字符串中的指定字符,方法二使用起来更加简便和易读。需要根据实际情况选择合适的方法来实现。

  
  

评论区