Toggle the Case of Each Character in a String
Last Updated :
14 Jul, 2025
Given a string s consisting of English letters (both uppercase and lowercase), convert each character to its opposite case that is, change every lowercase letter to uppercase, and every uppercase letter to lowercase.
Examples:
Input : s = "geeksForgEeks"
Output : "GEEKSfORGeEKS"
Explanation : All lower case characters are changed into upper case and vice versa.
Input : s = "capiTAlize"
Output : "CAPItaLIZE"
Explanation : All lower case characters are changed into upper case and vice versa.
Input : s = "SMALLcase"
Output : "smallCASE"
Explanation : All lower case characters are changed into upper case and vice versa.
[Naive Approach] Using index() method - O(n) Time and O(n) space
The primary idea involves use of two fixed lookup strings, one for uppercase and one for lowercase, and for each character finds its index in one string to pick the corresponding opposite‑case character from the other, building a new toggled string.
C++
#include <iostream>
using namespace std;
string toggleChar(string& str) {
string result = "";
string uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string lowalpha = "abcdefghijklmnopqrstuvwxyz";
// Iterate over each character in the input string
for (char ch : str) {
// If character is uppercase, find its position
// and get the corresponding lowercase
if (uppalpha.find(ch) != string::npos) {
result += lowalpha[uppalpha.find(ch)];
} else {
result += uppalpha[lowalpha.find(ch)];
}
}
return result;
}
int main() {
string str = "GeEkSfOrGeEkS";
string converted = toggleChar(str);
cout << converted << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* toggleChar(char* input) {
char uppalpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char lowalpha[] = "abcdefghijklmnopqrstuvwxyz";
int len = strlen(input);
char* output = (char*)malloc((len + 1) * sizeof(char));
if (output == NULL) {
return NULL;
}
// Iterate over each character in the input string
for (int i = 0; i < len; i++) {
char ch = input[i];
// If character is uppercase, find its position
// and get the corresponding lowercase
if (strchr(uppalpha, ch)) {
int j = strchr(uppalpha, ch) - uppalpha;
output[i] = lowalpha[j];
} else {
int j = strchr(lowalpha, ch) - lowalpha;
output[i] = uppalpha[j];
}
}
output[len] = '\0';
return output;
}
int main() {
char str[] = "GeEkSfOrGeEkS";
char* toggled = toggleChar(str);
printf("%s\n", toggled);
return 0;
}
Java
public class GFG {
public static String toggleChar(String str) {
String result = "";
String uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowalpha = "abcdefghijklmnopqrstuvwxyz";
// Iterate over each character in the input string
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// If character is uppercase, find its position
// and get the corresponding lowercase
if (uppalpha.indexOf(ch) != -1) {
result += lowalpha.charAt(uppalpha.indexOf(ch));
} else {
result += uppalpha.charAt(lowalpha.indexOf(ch));
}
}
return result;
}
public static void main(String[] args) {
String str = "GeEkSfOrGeEkS";
String toggled = toggleChar(str);
System.out.println(toggled);
}
}
Python
def toggleChar(s):
uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowalpha = "abcdefghijklmnopqrstuvwxyz"
result = ""
# Iterate over each character in the input string
for i in s:
# If character is uppercase, find its position
# and get the corresponding lowercase
if i in uppalpha:
result += lowalpha[uppalpha.index(i)]
else:
result += uppalpha[lowalpha.index(i)]
return result
if __name__ == "__main__":
str = "GeEkSfOrGeEkS"
x = toggleChar(str)
print(x)
C#
using System;
public class GFG{
public static string ToggleChar(string str){
string uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string lowalpha = "abcdefghijklmnopqrstuvwxyz";
string result = "";
// Iterate over each character in the input string
for (int i = 0; i < str.Length; i++){
char ch = str[i];
// If character is uppercase, find its position
// and get the corresponding lowercase
if (uppalpha.IndexOf(ch) != -1){
result += lowalpha[uppalpha.IndexOf(ch)];
}
else{
result += uppalpha[lowalpha.IndexOf(ch)];
}
}
return result;
}
public static void Main(string[] args){
string str = "GeEkSfOrGeEkS";
string x = ToggleChar(str);
Console.WriteLine(x);
}
}
JavaScript
function toggleChar(str) {
let result = "";
let uppalpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let lowalpha = "abcdefghijklmnopqrstuvwxyz";
// Iterate over each character in the input string
for (let i = 0; i < str.length; i++) {
let ch = str[i];
// If character is uppercase, find its position
// and get the corresponding lowercase and vice versa
if (uppalpha.indexOf(ch) !== -1) {
result += lowalpha[uppalpha.indexOf(ch)];
} else {
result += uppalpha[lowalpha.indexOf(ch)];
}
}
return result;
}
// Driver Code
let str = "GeEkSfOrGeEkS";
let x = toggleChar(str);
console.log(x);
[Approach 1] Using ASCII values - O(n) Time and O(1) Space
The main logic is to iterate through each character of the string and toggle its case using ASCII values: subtract 32 to convert lowercase to uppercase, and add 32 to convert uppercase to lowercase.
ASCII values of alphabets: A - Z = 65 to 90 and a - z = 97 to 122
Step By Step Implementation :
- Take one string of any length and calculate its length.
- Scan string character by character and keep checking the index.
- If a character in an index is in lower case, then subtract 32 to convert it into upper case, else add 32 to convert it in lowercase
C++
#include <iostream>
using namespace std;
string toggleChar(string &str) {
int ln = str.length();
// Conversion according to ASCII values
for (int i = 0; i < ln; i++) {
if (str[i] >= 'a' && str[i] <= 'z')
// Convert lowercase to uppercase
str[i] = str[i] - 32;
else if (str[i] >= 'A' && str[i] <= 'Z')
// Convert uppercase to lowercase
str[i] = str[i] + 32;
}
return str;
}
int main() {
string str = "GeEkSfOrGeEkS";
str = toggleChar(str);
cout << str;
return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* toggleChar(char* str){
int ln = strlen(str);
char* result = (char*)malloc((ln + 1) * sizeof(char));
// Conversion according to ASCII values
for (int i = 0; i < ln; i++) {
if (str[i] >= 'a' && str[i] <= 'z')
// Convert lowercase to uppercase
result[i] = str[i] - 32;
else if (str[i] >= 'A' && str[i] <= 'Z')
// Convert uppercase to lowercase
result[i] = str[i] + 32;
else
result[i] = str[i];
}
result[ln] = '\0';
return result;
}
int main(){
char str[] = "GeEkSfOrGeEkS";
char* toggled = toggleChar(str);
printf("%s", toggled);
return 0;
}
Java
public class GFG {
public static String toggleChar(String str) {
int ln = str.length();
// Conversion according to ASCII values
char[] arr = str.toCharArray();
for (int i = 0; i < ln; i++) {
if (arr[i] >= 'a' && arr[i] <= 'z')
// Convert lowercase to uppercase
arr[i] = (char)(arr[i] - 32);
else if (arr[i] >= 'A' && arr[i] <= 'Z')
// Convert uppercase to lowercase
arr[i] = (char)(arr[i] + 32);
}
return new String(arr);
}
public static void main(String[] args) {
String str = "GeEkSfOrGeEkS";
str = toggleChar(str);
System.out.println(str);
}
}
Python
def toggleChar(str):
ln = len(str)
# Conversion according to ASCII values
for i in range(ln):
if str[i] >= 'a' and str[i] <= 'z':
# Convert lowercase to uppercase
str[i] = chr(ord(str[i]) - 32)
elif str[i] >= 'A' and str[i] <= 'Z':
# Convert lowercase to uppercase
str[i] = chr(ord(str[i]) + 32)
if __name__ == "__main__":
str = "GeEkSfOrGeEkS"
str = list(str)
toggleChar(str)
str = ''.join(str)
print(str)
C#
using System;
using System.Text;
class GFG {
static string toggleChar(string str){
int ln = str.Length;
StringBuilder result = new StringBuilder(str);
// Conversion according to ASCII values
for (int i = 0; i < ln; i++){
if (result[i] >= 'a' && result[i] <= 'z')
// Convert lowercase to uppercase
result[i] = (char)(result[i] - 32);
else if (result[i] >= 'A' && result[i] <= 'Z')
// Convert uppercase to lowercase
result[i] = (char)(result[i] + 32);
}
return result.ToString();
}
public static void Main() {
string str = "GeEkSfOrGeEkS";
string toggled = toggleChar(str);
Console.WriteLine(toggled);
}
}
JavaScript
function toggleChar(str) {
const chars = str.split('');
const ln = chars.length;
// Conversion according to ASCII values
for (let i = 0; i < ln; i++) {
const code = chars[i].charCodeAt(0);
if (code >= 97 && code <= 122) {
// Convert lowercase to uppercase (subtract 32)
chars[i] = String.fromCharCode(code - 32);
} else if (code >= 65 && code <= 90) {
// Convert uppercase to lowercase (add 32)
chars[i] = String.fromCharCode(code + 32);
}
}
return chars.join('');
}
// Driver Code
const str = "GeEkSfOrGeEkS";
console.log(toggleChar(str));
[Approach 2] Toggle Case Using XOR on 5th Bit - O(n) Time and O(1) Space
The core logic behind letter case toggling is based on the ASCII representation of characters. In ASCII, the difference between any lowercase and its corresponding uppercase letter is always 32 — for example, 'a' - 'A' = 32, 'b' - 'B' = 32, and so on. This means that toggling the 5th bit (i.e., 1 << 5 = 32) of an alphabetic character using XOR (ch ^= 1 << 5) effectively switches its case — converting lowercase to uppercase and vice versa — in constant time.
Step By Step Implementation :
- Traverse the given string S.
- For each character, Si, do Si = Si^ (1 << 5).Si^ (1 << 5) toggles the 5thbit which means 97 will become 65 and 65 will become 97:
- Print the string after all operations
C++
#include <iostream>
using namespace std;
string toggleChar(string& S) {
string result = S;
// Iterate over the string in order to flip the 5th bit.
for (auto& ch : result) {
if (isalpha(ch)) {
// Toggle the 5th bit to flip case
ch ^= (1 << 5);
}
}
return result;
}
int main() {
string S = "GeEkSfOrGeEkS";
string toggled = toggleChar(S);
cout << toggled << endl;
return 0;
}
C
#include <stdio.h>
#include <ctype.h>
char* toggleChar(char *S) {
// Iterate over the string in order to flip the 5th bit.
for (int i = 0; S[i] != '\0'; ++i) {
if (isalpha((char)S[i])) {
// Toggle the 5th bit to flip case
S[i] ^= (1 << 5);
}
}
return S;
}
int main(void) {
char S[] = "GeEkSfOrGeEkS";
char* toggled = toggleChar(S);
printf("%s\n", toggled);
return 0;
}
Java
class GFG {
static String toggleChar(String input) {
// Convert string to char array
char[] chars = input.toCharArray();
// Iterate over the string in order to flip the 5th bit.
for (int i = 0; i < chars.length; i++) {
if (Character.isAlphabetic(chars[i])) {
// Toggle the 5th bit to flip case
chars[i] ^= (1 << 5);
}
}
return new String(chars);
}
public static void main(String[] args) {
String S = "GeEkSfOrGeEkS";
String toggled = toggleChar(S);
System.out.println(toggled);
}
}
Python
def toggleChar(s):
ans = ""
# Iterate over the string in order to flip the 5th bit.
for ch in s:
# Toggle the 5th bit to flip case
ans += chr(ord(ch) ^ (1 << 5))
return ans
if __name__ == "__main__":
s = "GeEkSfOrGeEkS"
result = toggleChar(s)
print(result)
C#
using System;
class GFG {
static string toggleChar(string input){
// Iterate over the string in order to flip the 5th bit.
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++) {
if (char.IsLetter(chars[i])) {
// Toggle the 5th bit to flip case
chars[i] = (char)(chars[i] ^ (1 << 5));
}
}
return new string(chars);
}
public static void Main(string[] args){
string S = "GeEkSfOrGeEkS";
string toggled = toggleChar(S);
Console.WriteLine(toggled);
}
}
JavaScript
function toggleChar(str) {
const chars = str.split('');
for (let i = 0; i < chars.length; i++) {
const code = chars[i].charCodeAt(0);
// Iterate over the string in order to flip the 5th bit.
if ((code >= 65 && code <= 90) ||
(code >= 97 && code <= 122)) {
// Toggle the 5th bit to flip case
chars[i] = String.fromCharCode(code ^ (1 << 5));
}
}
return chars.join('');
}
// Driver code
const s = "GeEkSfOrGeEkS";
console.log(toggleChar(s));
[Approach 3] Library-Based Case Toggling - O(n) Time and O(1) Space
The idea involves initializing an empty string. Iterate a for loop over the given string and check each character whether is lowercase or uppercase using isupper() and islower().If lowercase converts the character to uppercase using upper() and append to empty string, similarly with uppercase.
C++
#include <iostream>
#include <cctype>
using namespace std;
string toggleChar(string& str) {
string result = "";
// Iterate over the original string
for (int i = 0; i < str.length(); i++) {
char ch = str[i];
// Check the case of the character and
// toggle accordingly
if (isupper(ch))
result += tolower(ch);
else
result += toupper(ch);
}
return result;
}
int main() {
string str = "GeEkSfOrGeEkS";
string x = toggleChar(str);
cout << x << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char* toggleChar(char* str) {
int len = strlen(str);
char* result = (char*)malloc(len + 1);
// Iterate over the original string
for (int i = 0; i < len; i++) {
char ch = str[i];
// Check the case of the character and
// toggle accordingly
if (isupper((unsigned char)ch))
result[i] = tolower((unsigned char)ch);
else
result[i] = toupper((unsigned char)ch);
}
result[len] = '\0';
return result;
}
int main() {
const char* str = "GeEkSfOrGeEkS";
char* x = toggleChar(str);
printf("%s\n", x);
free(x);
return 0;
}
Java
public class GFG {
public static String toggleChar(String str) {
String result = "";
// Iterate over the original string
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// Check the case of the character and
// toggle accordingly
if (Character.isUpperCase(ch))
result += Character.toLowerCase(ch);
else
result += Character.toUpperCase(ch);
}
return result;
}
public static void main(String[] args) {
String str = "GeEkSfOrGeEkS";
String x = toggleChar(str);
System.out.println(x);
}
}
Python
def toggleChar(str):
result = ""
# Iterate over the original string
for i in range(len(str)):
ch = str[i]
# Check the case of the character and
# toggle accordingly
if ch.isupper():
result += ch.lower()
else:
result += ch.upper()
return result
if __name__ == "__main__":
str = "GeEkSfOrGeEkS"
x = toggleChar(str)
print(x)
C#
using System;
class Program {
static string toggleChar(string str) {
string result = "";
// Iterate over the original string
for (int i = 0; i < str.Length; i++) {
char ch = str[i];
// Check the case of the character and
// toggle accordingly
if (char.IsUpper(ch))
result += char.ToLower(ch);
else
result += char.ToUpper(ch);
}
return result;
}
static void Main() {
string str = "GeEkSfOrGeEkS";
string x = toggleChar(str);
Console.WriteLine(x);
}
}
JavaScript
function toggleChar(str) {
let result = "";
// Iterate over the original string
for (let i = 0; i < str.length; i++) {
const ch = str[i];
// Check the case of the character and
// toggle accordingly
if (ch === ch.toUpperCase())
result += ch.toLowerCase();
else
result += ch.toUpperCase();
}
return result;
}
// Driver Code
const str = "GeEkSfOrGeEkS";
const x = toggleChar(str);
console.log(x);
[Approach 4] Using Transform Function - O(n) Time and O(1) Space
This implementation performs an in‑place pass over the string and, at each position, invokes std::transform on a single‑character iterator range—applying ::tolower or ::toupper—to toggle the case of that character using the STL’s functional algorithm.
Note :- The "Transform Function" is only available in C++.
C++
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
string toggleChar(string str) {
// Iterate over the string
for (int i = 0; i < str.length(); i++) {
// Check the case of character and
// use transform function accordingly
if (isupper(str[i])) {
transform(str.begin() + i,
str.begin() + i + 1, str.begin() + i, ::tolower);
} else {
transform(str.begin() + i,
str.begin() + i + 1, str.begin() + i, ::toupper);
}
}
return str;
}
int main() {
string str = "GeEkSfOrGeEkS";
string result = toggleChar(str);
cout << result << endl;
return 0;
}
[Approach 5] Pointer Based Approach - O(n) Time and O(1) Space
The main logic is, obtain a raw pointer to the string’s internal buffer (&str[0]) and then walk it character by character until the null terminator, using the <cctype> predicates and converters (isupper/tolower and toupper) to flip each letter’s case in‑place.
Note :- We get pointer based approach in C and C++ only.
C++
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
string toggleChar(string str) {
// Point to the first character
char* p = &str[0];
// Use pointer to traverse through the string
// change uppercase character to lower case
// and vice-versa
while (*p != '\0') {
if (isupper(static_cast<unsigned char>(*p))) {
*p = tolower(static_cast<unsigned char>(*p));
} else {
*p = toupper(static_cast<unsigned char>(*p));
}
++p;
}
return str;
}
int main() {
string str = "GeEkSfOrGeEkS";
str = toggleChar(str);
cout << str << endl;
return 0;
}
C
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char* toggleChar(char* str) {
// Point to the first character
char* p = str;
// Use pointer to traverse through the string
// change uppercase character to lower case
// and vice-versa
while (*p != '\0') {
if (isupper((unsigned char)*p)) {
*p = tolower((unsigned char)*p);
} else {
*p = toupper((unsigned char)*p);
}
++p;
}
return str;
}
int main() {
char str[] = "GeEkSfOrGeEkS";
printf("%s\n", toggleChar(str));
return 0;
}
CPP Program to Convert Lowercase to Uppercase & vice versa
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem