C++字符串查找:判断字符是否存在于'gdufe'中
C++字符串查找:判断字符是否存在于'gdufe'中
这篇文章提供了一个C++代码示例,用于判断输入的字符是否存在于字符串'gdufe'中。
代码功能:
- 接收用户输入的测试用例数量。2. 循环读取每个测试用例,每个用例包含一个待查找的小写字母。3. 使用
find函数查找该字母是否存在于字符串 'gdufe' 中。4. 输出 'YES' 或 'NO' 表示查找结果。
**C++代码示例:**cpp#include
int main() { int t; std::cout << '请输入测试用例的数量t:' << std::endl; std::cin >> t;
std::string target = 'gdufe';
for (int i = 0; i < t; ++i) { char c; std::cout << '请输入一个小写字母c:' << std::endl; std::cin >> c;
std::string result = 'NO'; if (target.find(c) != std::string::npos) { result = 'YES'; }
std::cout << result << std::endl; }
return 0;}
代码解释:
#include <iostream>和#include <string>: 引入必要的头文件,用于输入输出和字符串操作。-std::cin >> t;: 读取用户输入的测试用例数量。-std::string target = 'gdufe';: 定义目标字符串 'gdufe'。-for (int i = 0; i < t; ++i): 循环处理每个测试用例。-char c; std::cin >> c;: 读取用户输入的待查找字符。-target.find(c): 在目标字符串中查找字符c。-std::string::npos: 如果未找到字符,find函数返回std::string::npos。-result = 'YES';: 如果找到字符,将结果设置为 'YES'。-std::cout << result << std::endl;: 输出查找结果。
如何使用代码:
- 将代码复制到本地C++编译器中。2. 编译并运行代码。3. 按照提示输入测试用例数量和待查找的字符。4. 程序会输出每个测试用例的查找结果 ('YES' 或 'NO')。
希望这个例子能帮助您理解如何使用C++进行字符串查找!
原文地址: https://www.cveoy.top/t/topic/Npw 著作权归作者所有。请勿转载和采集!