Program to toggle all characters in a string
Last Updated :
01 Mar, 2023
Given a string, the task is to toggle all the characters of the string i.e to convert Upper case to Lower case and vice versa.
Examples:
Input : gfg
Output : GFG
Input : aBc12#
Output : AbC12#
Input : tu@kmiNi
Output : TU@KMInI
Traverse the given string, if uppercase characters come, convert into lowercase and lowercase letter convert into uppercase.
Implementation:
C
// C program to toggle all characters
#include <stdio.h>
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';
}
}
// Driver code
int main()
{
char str[] = "GeKf@rGeek$";
toggleChars(str);
printf("String after toggle \n");
printf("%s\n", str);
return 0;
}
C++
// C++ program to toggle all characters
#include<bits/stdc++.h>
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';
}
}
// Driver code
int main()
{
char str[] = "GeKf@rGeek$";
toggleChars(str);
cout << "String after toggle " << endl;
cout << str << endl;
return 0;
}
Java
// Java program to toggle all characters
class GFG
{
static void toggleChars(char str[])
{
for (int i=0; i<str.length; i++)
{
if (str[i]>='A' && str[i]<='Z')
str[i] = (char) (str[i] + 'a' - 'A');
else if (str[i]>='a' && str[i]<='z')
str[i] = (char) (str[i] + 'A' - 'a');
}
}
// Driver code
public static void main(String[] args)
{
char str[] = "GeKf@rGeek$".toCharArray();
toggleChars(str);
System.out.println("String after toggle ");
System.out.println(String.valueOf(str));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to toggle all characters
def toggleChars(str):
for i in range(len(str)):
if (str[i] >= 'A' and str[i] <= 'Z'):
str = str[:i] + chr(ord(str[i]) + \
ord('a') - ord('A')) + str[i + 1:];
else if (str[i] >= 'a' and str[i] <= 'z'):
str = str[:i] + chr(ord(str[i]) + \
ord('A') - ord('a')) + str[i + 1:];
return str;
# Driver code
str = "GeKf@rGeek$";
str = toggleChars(str);
print(str);
# This code is contributed by 29AjayKumar
C#
// C# program to toggle all characters
using System;
class GFG
{
static void toggleChars(char []str)
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = (char) (str[i] + 'a' - 'A');
else if (str[i] >= 'a' && str[i] <= 'z')
str[i] = (char) (str[i] + 'A' - 'a');
}
}
// Driver code
public static void Main(String[] args)
{
char []str = "GeKf@rGeek$".ToCharArray();
toggleChars(str);
Console.WriteLine("String after toggle ");
Console.WriteLine(String.Join("",str));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
function toggleChars(str)
{
for (let i = 0; i < str.length; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0));
else if (str[i] >= 'a' && str[i] <= 'z')
str[i] = String.fromCharCode(str[i].charCodeAt(0) + 'A'.charCodeAt(0) - 'a'.charCodeAt(0));
}
}
let str = "GeKf@rGeek$".split("");
toggleChars(str);
document.write("String after toggle ");
document.write((str).join(""));
// This code is contributed by rag2127.
</script>
OutputString after toggle
gEkF@RgEEK$
Time complexity: O(n), where n is length of string
Auxiliary space: O(1)
We can use the Bitwise XOR operation to toggle all the characters in given string
As we know the ascii value of small and capital char case is differ by just 1 bit (5th bit). We can simply toggle that bit to toggle the char case of a string.
Implementation:
C
// C program to toggle all characters
#include <stdio.h>
void toggleChars(char str[])
{
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 65 && str[i] <= 90) {
str[i] = (char)(str[i] ^ (1 << 5));
}
}
}
// Driver code
int main()
{
char str[] = "GeKf@rGeek$";
printf("String before toggle\n");
printf("%s\n", str);
toggleChars(str);
printf("String after toggle\n");
printf("%s\n", str);
return 0;
}
C++
// C++ program to toggle all characters
#include<bits/stdc++.h>
using namespace std;
void toggleChars(char str[])
{
for (int i=0; str[i]!='\0'; i++)
{
if (isalpha(str[i])) {
str[i] = (char)(str[i]^(1<<5));
}
}
}
// Driver code
int main()
{
char str[] = "GeKf@rGeek$";
cout << "String before toggle " << endl;
cout << str << endl;
toggleChars(str);
cout << "String after toggle " << endl;
cout << str << endl;
return 0;
}
// This code is contributed by @kaustubhvats08
Java
// Java program to toggle all characters
class GFG
{
static void toggleChars(char str[])
{
for (int i=0; i<str.length; i++)
{
if (Character.isAlphabetic(str[i])) {
str[i] = (char)(str[i]^(1<<5));
}
}
}
// Driver code
public static void main(String[] args)
{
char str[] = "GeKf@rGeek$".toCharArray();
System.out.println("String before toggle ");
System.out.println(String.valueOf(str));
toggleChars(str);
System.out.println("String after toggle ");
System.out.println(String.valueOf(str));
}
}
// This code is contributed by @kaustubhvats08
Python3
# Python3 program to toggle all characters
def toggleChars(s):
for i in range(len(s)):
if s[i].isalpha():
s = s[:i] + str(chr(ord(s[i])^(1<<5))) + s[i+1:]
return s;
# Driver code
s = "GeKf@rGeek$";
print("String before toggle")
print(s)
s = toggleChars(s);
print("String after toggle")
print(s);
# This code is contributed by @kaustubhvats08
C#
// C# program to toggle all characters
using System;
class GFG
{
static void toggleChars(char []str)
{
for (int i = 0; i < str.Length; i++)
{
if (Char.IsLetter(str[i])){
str[i] = (char)(str[i]^(1<<5));
}
}
}
// Driver code
public static void Main(String[] args)
{
char []str = "GeKf@rGeek$".ToCharArray();
Console.WriteLine("String before toggle ");
Console.WriteLine(String.Join("",str));
toggleChars(str);
Console.WriteLine("String after toggle ");
Console.WriteLine(String.Join("",str));
}
}
// This code is contributed by @kaustubhvats08
JavaScript
<script>
function toggleChars(str)
{
for (let i = 0; i < str.length; i++)
{
if ((/[a-zA-Z]/).test(str[i])){
str[i] = (String.fromCharCode((str[i].charCodeAt(0)^(1<<5))));
}
}
}
let str = "GeKf@rGeek$".split("");
document.write("String before toggle ");
document.write((str).join(""));
toggleChars(str);
document.write("String after toggle ");
document.write((str).join(""));
// This code is contributed by @kaustubhvats08.
</script>
OutputString before toggle
GeKf@rGeek$
String after toggle
gEkF@RgEEK$
Time complexity: O(n), where n is the length of the string
Auxiliary space: O(1)
Similar Reads
Program for removing i-th character from a string Given a string S along with an integer i. Then your task is to remove ith character from S. Examples: Input: S = Hello World!, i = 7Output: Hello orld!Explanation: The Xth character is W and after removing it S becomes Hello orld! Input: S = GFG, i = 1Output: GGExplanation: It can be verified that a
5 min read
Quick way to check if all the characters of a string are same Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks"Output : No Input : s = "gggg" Output : Yes Recommended PracticeCheck StringTry It! Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and
8 min read
Convert characters of a string to opposite case Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput : hello every oneOutput : HELLO EVERY ONEASCII values of alphabets: A - Z = 65
15+ min read
Toggle characters in words having same case - Python We are given a sentence and need to toggle the case of words that have all characters in the same case, either all lowercase or all uppercase. If a word meets this condition, we change each letter to its opposite case using swapcase(). Words with a mix of uppercase and lowercase letters remain uncha
3 min read
Remove the first and last character of each word in a string Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
4 min read
Remove a Character from a Given Position Given a string and a position (0-based indexing), remove the character at the given position.Examples: Input : s = "abcde", pos = 1Output : s = "acde"Input : s = "a", pos = 0Output : s = ""Approach - By Using Built-In MethodsWe use erase in C++, string slicing in Python, StringBuilder Delete in Java
5 min read
Program to count vowels, consonant, digits and special characters in string. Given a string and the task is to count vowels, consonant, digits and special character in string. Special character also contains the white space.Examples: Input : str = "geeks for geeks121" Output : Vowels: 5 Consonant: 8 Digit: 3 Special Character: 2 Input : str = " A1 B@ d adc" Output : Vowels:
6 min read
Queries to flip characters of a binary string in given range Given a binary string, str and a 2D array Q[][] representing queries of the form {L, R}. In each query, toggle all the characters of the binary strings present in the indices [L, R]. The task is to print the binary string by performing all the queries. Examples: Input: str = "101010", Q[][] = { {0,
8 min read
Reverse a string without affecting special characters Given a string, that contains a special character together with alphabets ('a' to 'z' and 'A' to 'Z'), reverse the string in a way that special characters are not affected. Examples: Input: str = "a,b$c"Output: str = "c,b$a"Explanation: Note that $ and , are not moved anywhere. Only subsequence "abc
10 min read
Remove all characters other than alphabets from string Given a string consisting of alphabets and others characters, remove all the characters other than alphabets and print the string so formed. Examples: Input : $Gee*k;s..fo, r'Ge^eks?Output : GeeksforGeeks Input : P&ra+$BHa;;t*ku, ma$r@@s#in}ghOutput : PraBHatkumarsingh Recommended PracticeRemove
12 min read