C++ 字符串查找:寻找指定字符并返回最大下标

问题描述:

从给定字符串中查找某指定的字符,如果找到,输出该字符在字符串中所对应的最大下标(下标从 0 开始);否则输出 'Not Found'。

输入格式:

输入的第一行是一个待查找的字符。第二行是一个以回车结束的非空字符串(不超过 80 个字符)。

输出格式:

如果找到,在一行内按照格式 'index = 下标' 输出该字符在字符串中所对应的最大下标;否则输出 'Not Found'。

思路:

  1. 读入待查找的字符和字符串。
  2. 遍历字符串,寻找与待查找字符相同的字符。
  3. 记录找到的字符的最大下标。
  4. 如果找到匹配的字符,输出 'index = 下标',否则输出 'Not Found'。

参考代码:

#include <iostream>
#include <string>
using namespace std;

int main() {
    char target;  // 待查找的字符
    string str;   // 字符串
    int index = -1;  // 记录最大下标,初始化为 -1

    cin >> target >> str;

    for (int i = 0; i < str.length(); i++) {
        if (str[i] == target) {
            index = i;  // 更新最大下标
        }
    }

    if (index != -1) {
        cout << 'index = ' << index << endl;
    } else {
        cout << 'Not Found' << endl;
    }

    return 0;
}

代码解释:

  • #include <iostream>#include <string> 引入标准输入输出库和字符串库。
  • using namespace std; 将标准命名空间引入当前作用域。
  • char target; 声明一个字符变量 target 来存储待查找的字符。
  • string str; 声明一个字符串变量 str 来存储输入的字符串。
  • int index = -1; 声明一个整数变量 index 来存储找到的字符的最大下标,并初始化为 -1。
  • cin >> target >> str; 从标准输入读取待查找的字符和字符串。
  • for (int i = 0; i < str.length(); i++) {...} 使用循环遍历字符串。
  • if (str[i] == target) {...} 判断当前字符是否与待查找的字符相同。
  • index = i; 如果找到匹配的字符,更新最大下标 index 为当前字符的下标 i
  • if (index != -1) {...} 判断是否找到匹配的字符。
  • cout << 'index = ' << index << endl; 如果找到匹配的字符,输出 'index = 下标'。
  • cout << 'Not Found' << endl; 如果没有找到匹配的字符,输出 'Not Found'。

注意:

  • 该代码假设输入字符串中至少包含一个字符。
  • 代码中使用了 index = -1 来初始化 index,以便区分没有找到匹配的字符的情况。
  • 循环遍历字符串时,可以使用 str.length() 来获取字符串长度。
  • 可以根据需要修改代码,例如增加对输入字符串长度的限制等。

总结:

本程序实现了从给定字符串中查找指定字符的功能,并返回该字符在字符串中出现的最大下标。代码清晰易懂,并提供详细的思路和注释,适合初学者学习。

C++ 字符串查找:寻找指定字符并返回最大下标

原文地址: https://www.cveoy.top/t/topic/mGG5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录