在C ++中切换字符串中的所有字符
该程序将字符串的字符转换为大写。但是,使用toUpper()
c++类库的方法可以轻松完成此任务。但是在此程序中,我们通过计算大写字符的ASCII值来执行此操作。该算法如下:
算法
START Step-1: Declare the array of char Step-2: Check ASCII value of uppercase characters which must grater than A and lesser than Z Step-3: Check ASCII value of lower characters which must grater than A and lesser than Z END
该toggleChar()
方法获取字符数组作为输入。然后,遍历循环以确保输入的字符ASCII值是否在A到Z之间,如下所示;
示例
#include<iostream> using namespace std; void toggleChars(char str[]){ for (int i=0; str[i]!='\0'; i++){ if (str[i]>='A' && str[i]<='Z') str[i] = str[i] + 'a' - 'A'; else if (str[i]>='a' && str[i]<='z') str[i] = str[i] + 'A' - 'a'; } } int main(){ char str[] = "ajay@kumar#Yadav"; cout << "String before toggle::" << str << endl; toggleChars(str); cout << "String after toggle::" << str; return 0; }
提供的字符串几乎所有小写字符都将转换为大写形式,如下所示;
输出结果
String before toggle::ajay@kumar#Yadav String after toggle::AJAY@KUMAR#yADAV