在 C++ 中,INLINECODEe2461391 和 INLINECODE657a7c39 是我们用于处理字符串和字符的预定义函数。通常,INLINECODEb0084509 是处理字符串所需的头文件,而 INLINECODEcfcf0fb4 则是处理字符函数所需的头文件。
isupper() 函数
这个函数主要用于检查参数中是否包含大写字母,例如 A、B、C、D,…,Z。
**语法:**
int isupper(int x)
让我们来看看下面的 C++ 代码示例,了解如何使用 isupper() 来检查一个字符是否为大写。
// Program to check if a character is in
// uppercase using isupper()
#include
#include
using namespace std;
int main()
{
char x;
cin >> x;
if (isupper(x))
cout << "Uppercase";
else
cout << "Not uppercase.";
return 0;
}
输出
Not uppercase.
这个函数主要用于检查参数中是否包含小写字母,例如 a、b、c、d,…,z。
**语法:**
int islower(int x)
同样地,我们可以参考下面的 C++ 代码,看看如何使用 islower() 来判断字符是否为小写。
// Program to check if a character is in
// lowercase using islower()
#include
#include
using namespace std;
int main()
{
char x;
cin >> x;
if (islower(x))
cout << "Lowercase";
else
cout << "Not Lowercase.";
return 0;
}
输出
Not Lowercase.
islower()、isupper()、tolower() 和 toupper() 函数的实际应用
现在,让我们探讨这些函数的一个具体应用场景:给定一个字符串,我们的任务是将字符串中的字符转换为相反的大小写形式。也就是说,如果字符是小写,我们需要将其转换为大写;反之亦然。
**tolower() 的语法:**
int tolower(int ch);
**toupper() 的语法:**
int toupper(int ch);
示例:
输入 : GeekS
输出 :gEEKs
输入 :Test Case
输出 :tEST cASE
实现这一功能的逻辑如下:
- 遍历给定的字符串,逐个检查字符直到其长度结束,利用预定义函数判断字符是小写还是大写。
- 如果是小写,使用 INLINECODE493b4e3b 函数将其转换为大写;如果是大写,使用 INLINECODE74748cd7 函数将其转换为小写。
- 最后打印出转换后的字符串。
实现代码:
// C++ program to toggle cases of a given
// string.
#include
#include
using namespace std;
// function to toggle cases of a string
void toggle(string& str)
{
int length = str.length();
for (int i = 0; i < length; i++) {
int c = str[i];
if (islower(c))
str[i] = toupper(c);
else if (isupper(c))
str[i] = tolower(c);
}
}
// Driver Code
int main()
{
string str = "GeekS";
toggle(str);
cout << str;
return 0;
}
输出
gEEKs
时间复杂度 : O(n)
辅助空间 : O(1)