Toggle all characters in the string in C++


This program translates the characters of a string into uppercase. However, this task can be easily achieved by using the toUpper() method of the c++ class library. But in this program, we perform this by calculating the ASCII value of characters in uppercase. The Algorithm is as follows;

Algorithm

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

The toggleChar() method gets the array of characters as an input. Then, traverse through the loop to ensure whether the entered character ASCII value is in the between of the A to Z or not, as following;

Example

 Live Demo

#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;
}

The supplied string has almost all characters in lower case which will be converted in uppercase as following;

Output

String before toggle::ajay@kumar#Yadav
String after toggle::AJAY@KUMAR#yADAV

Updated on: 29-Nov-2019

670 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements