在本教程中,我们将学习如何在给定的字符串中找到第一个大写字母。让我们来看一个例子。
输入-Nhooo
输出-T
让我们看看使用迭代方法解决问题的步骤。
初始化字符串。
遍历字符串。
使用isupper方法检查当前字符是否为大写。
如果字符是大写字母,则返回当前字符。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str) {
for (int i = 0; i < str.length(); i++)
if (isupper(str[i])) {
return str[i];
}
return 0;
}
int main() {
string str = "Nhooo";
char result = firstUpperCaseChar(str);
if (result == 0) {
cout << "No uppercase letter" << endl;
}
else {
cout << result << endl;
}
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
T
让我们看看使用递归方法解决问题的步骤。
初始化字符串。
编写一个接受两个参数字符串和索引的递归函数。
如果当前字符是字符串的结尾,则返回。
如果当前字符是大写字母,则返回当前字符。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str, int i = 0) {
if (str[i] == '\0') {
return 0;
}
if (isupper(str[i])) {
return str[i];
}
return firstUpperCaseChar(str, i + 1);
}
int main() {
string str = "Nhooo";
char result = firstUpperCaseChar(str);
if (result == 0) {
cout << "No uppercase letter";
}
else {
cout << result << endl;
}
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
T
如果您对本教程有任何疑问,请在评论部分中提及。