Open In App

Convert characters of a string to opposite case

Last Updated : 17 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 : geeksForgEeks
Output : GEEKSfORGeEKS
Input : hello every one
Output : HELLO EVERY ONE

ASCII values  of alphabets: A – Z = 65 to 90, a – z = 97 to 122 

Steps: 

  1. Take one string of any length and calculate its length.
  2. 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
  3. Print the final string.

Implementation:

C++




// CPP program to Convert characters
// of a string to opposite case
#include <iostream>
using namespace std;
 
// Function to convert characters
// of a string to opposite case
void convertOpposite(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;
    }
}
 
// Driver function
int main()
{
    string str = "GeEkSfOrGeEkS";
 
    // Calling the Function
    convertOpposite(str);
 
    cout << str;
    return 0;
}


C




// C program to Convert characters
// of a string to opposite case
 
#include <stdio.h>
#include <string.h>
 
// Function to convert characters
// of a string to opposite case
void convertOpposite(char* str)
{
    int ln = strlen(str);
 
    // 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;
    }
}
 
// Driver function
int main()
{
    char str[] = "GeEkSfOrGeEkS";
 
    // Calling the Function
    convertOpposite(str);
 
    printf("%s", str);
    return 0;
}


Java




// Java program to Convert characters
// of a string to opposite case
class Test {
 
    // Method to convert characters
    // of a string to opposite case
    static void convertOpposite(StringBuffer str)
    {
        int ln = str.length();
 
        // Conversion using predefined methods
        for (int i = 0; i < ln; i++) {
            Character c = str.charAt(i);
            if (Character.isLowerCase(c))
                str.replace(i, i + 1,
                            Character.toUpperCase(c) + "");
            else
                str.replace(i, i + 1,
                            Character.toLowerCase(c) + "");
        }
    }
 
    public static void main(String[] args)
    {
        StringBuffer str
            = new StringBuffer("GeEkSfOrGeEkS");
        // Calling the Method
        convertOpposite(str);
 
        System.out.println(str);
    }
}
// This code is contributed by Gaurav Miglani


Python3




# Python3 program to Convert characters
# of a string to opposite case
 
# Function to convert characters
# of a string to opposite case
def convertOpposite(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)
 
# Driver code
if __name__ == "__main__":
    str = "GeEkSfOrGeEkS"
    str = list(str)
 
    # Calling the Function
    convertOpposite(str)
 
    str = ''.join(str)
    print(str)
 
# This code is contributed by
# sanjeev2552


C#




// C# program to Convert characters
// of a string to opposite case
using System;
using System.Text;
 
class GFG{
     
    // Method to convert characters
    // of a string to opposite case
    static void convertOpposite(StringBuilder 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] = (char)(str[i] - 32);
                 
            else if(str[i]>='A' && str[i]<='Z')
             
                //Convert uppercase to lowercase
                str[i] = (char)(str[i] + 32);
        }
    }
     
    // Driver code
    public static void Main()
    {
        StringBuilder str = new StringBuilder("GeEkSfOrGeEkS");
        // Calling the Method
        convertOpposite(str);
        Console.WriteLine(str);
        }
}
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Function to convert characters
// of a string to opposite case
function convertOpposite(str)
{
    var ln = str.length;
 
    // Conversion according to ASCII values
    for (var i = 0; i < ln; i++)
    {
        if (str[i] >= 'a' && str[i] <= 'z')
            // Convert lowercase to uppercase
            document.write(
            String.fromCharCode(str.charCodeAt(i) - 32)
            );
        else if (str[i] >= 'A' && str[i] <= 'Z')
            // Convert uppercase to lowercase
            document.write(
            String.fromCharCode(str.charCodeAt(i) + 32)
            );
    }
}
 
// Driver function
var str = "GeEkSfOrGeEkS";
 
    // Calling the Function
    convertOpposite(str);
 
</script>


PHP




<?php
     
// Function to convert characters
// of a string to opposite case
function convertOpposite($str)
{
    $ln = strlen($str);
 
    // Conversion according to ASCII values
    for ($i = 0; $i < $ln; $i++)
    {
        if ($str[$i] >= 'a' && $str[$i] <= 'z'){
            // Convert lowercase to uppercase
            $str[$i] = strtoupper($str[$i]); 
        }
        else if ($str[$i] >= 'A' && $str[$i] <= 'Z'){
            // Convert uppercase to lowercase
            $str[$i] = strtolower($str[$i]);
        }
    }
  return $str;
}
 
// Driver function
$str = "GeEkSfOrGeEkS";
 
    // Calling the Function
echo(convertOpposite($str));
   
// This code is contributed by ksrikanth0498
   
?>


Output

gEeKsFoRgEeKs





Time Complexity: O(n) 

Note: This program can alternatively be done using C++ inbuilt functions – Character.toLowerCase(char) and Character.toUpperCase(char). 

Approach 2: The problem can be solved using letter case toggling. Follow the below steps to solve the problem:

  • Traverse the given string S.
  • For each character, Si, do Si =  Si ^ (1 << 5).
  • Si ^ (1 << 5) toggles the 5th bit which means 97 will become 65 and 65 will become 97:
    • 65 ^ 32 = 97
    • 97 ^ 32 = 65 
  • Print the string after all operations

Below is the implementation of the above approach:

C++




// C++ program to toggle all characters
#include <bits/stdc++.h>
using namespace std;
 
// Function to toggle characters
void toggleChars(string& S)
{
    for (auto& it : S) {
        if (isalpha(it)) {
            it ^= (1 << 5);
        }
    }
}
 
// Driver code
int main()
{
    string S = "GeKf@rGeek$";
    toggleChars(S);
    cout << "String after toggle " << endl;
    cout << S << endl;
    return 0;
}
 
// Code contributed by koulick_sadhu


C




// C program to toggle all characters
 
#include <ctype.h>
#include <stdio.h>
 
// Function to toggle characters
void toggleChars(char* S)
{
    while (*S) {
        if (isalpha(*S)) {
            *S ^= (1 << 5);
        }
        ++S;
    }
}
 
// Driver code
int main()
{
    char S[] = "GeKf@rGeek$";
    toggleChars(S);
    printf("String after toggle:\n%s\n", S);
    return 0;
}


Java




// Java program to toggle all characters
import java.util.*;
 
class GFG {
 
    static char[] S = "GeKf@rGeek$".toCharArray();
 
    // Function to toggle characters
    static void toggleChars()
    {
        for (int i = 0; i < S.length; i++) {
            if (Character.isAlphabetic(S[i])) {
                S[i] ^= (1 << 5);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        toggleChars();
        System.out.print("String after toggle "
                         + "\n");
        System.out.print(String.valueOf(S));
    }
}
 
// This code is contributed by Amit Katiyar


Python3




# python program for the same approach
def isalpha(input):
    input_char = ord(input[0])
 
    # CHECKING FOR ALPHABET
    if((input_char >= 65 and input_char <= 90) or (input_char >= 97 and input_char <= 122)):
        return True
    else:
        return False
 
# Function to toggle characters
 
 
def toggleChars(S):
    s = ""
 
    for it in range(len(S)):
 
        if(isalpha(S[it])):
            s += chr(ord(S[it]) ^ (1 << 5))
        else:
            s += S[it]
 
    return s
 
 
# Driver code
S = "GeKf@rGeek$"
print(f"String after toggle {toggleChars(S)}")
 
# This code is contributed by shinjanpatra


C#




// C# program to toggle all characters
using System;
 
class GFG {
 
    static char[] S = "GeKf@rGeek$".ToCharArray();
 
    // Function to toggle characters
    static void toggleChars()
    {
        for (int i = 0; i < S.Length; i++) {
            if (char.IsLetter(S[i])) {
                S[i] = (char)((int)(S[i]) ^ (1 << 5));
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        toggleChars();
        Console.Write("String after toggle "
                      + "\n");
        Console.Write(String.Join("", S));
    }
}
 
// This code is contributed by Princi Singh


Javascript




<script>
  
 function isalpha(input)
 {
        var input_char = input.charCodeAt(0);
          
        // CHECKING FOR ALPHABET
        if (
          (input_char >= 65 && input_char <= 90) ||
          (input_char >= 97 && input_char <= 122))
        {
              return true;
          }
          else
          {
              return false;
          }
  
 }
  
// Function to toggle characters
function toggleChars(S)
{
var s = "";
 
    for(var it = 0; it < S.length; it++)
    {
       if(isalpha(S.charAt(it)))
       {
         s += String.fromCharCode(S.charCodeAt(it)^(1<<5)) 
       }
       else{
       s += S.charAt(it);
       }
    }
    return s;
}
  
// Driver code
var S = "GeKf@rGeek$";
document.write( "String after toggle " +toggleChars(S));
</script>
 
// This code is contributed by Akshit Saxena


Output

String after toggle 
gEkF@RgEEK$





 

Time Complexity: O(n)

Approach : Using isupper() and islower(),upper() and lower().

Initialize 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++




// C++ program to Convert characters
// of a string to opposite case
 
#include <iostream>
using namespace std;
 
int main()
{
 
    string str = "GeEkSfOrGeEkS";
    string x = "";
    for (int i = 0; i < str.length(); i++) {
        char ch = str[i];
        if (isupper(ch))
            x += tolower(ch);
        else
            x += toupper(ch);
    }
    cout << x << endl;
    return 0;
}
 
// This code is contributed by lokeshmvs21.


C




// C program to Convert characters
// of a string to opposite case
 
#include <ctype.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[] = "GeEkSfOrGeEkS";
    char x[100];
    for (int i = 0; i < strlen(str); i++) {
        char ch = str[i];
        if (isupper(ch))
            x[i] = tolower(ch);
        else
            x[i] = toupper(ch);
    }
    x[strlen(str)] = '\0';
    printf("%s\n", x);
    return 0;
}


Java




// Java program to Convert characters
// of a string to opposite case
import java.io.*;
 
class GFG {
  public static void main(String[] args)
  {
    String str = "GeEkSfOrGeEkS";
    String x = "";
    for (int i = 0; i < str.length(); i++) {
      char ch = str.charAt(i);
      if (Character.isUpperCase(ch))
        x += Character.toLowerCase(ch);
      else
        x += Character.toUpperCase(ch);
    }
    System.out.println(x);
  }
}
 
// This code is contributed by karandeep1234.


Python3




# Python3 program to Convert characters
# of a string to opposite case
 
str = "GeEkSfOrGeEkS"
x=""
for i in str:
    if(i.isupper()):
        x+=i.lower()
    else:
        x+=i.upper()
print(x)


C#




// C# program to Convert characters
// of a string to opposite case
using System;
 
public class GFG {
 
  static public void Main()
  {
 
    // Code
    string str = "GeEkSfOrGeEkS";
    string x = "";
    for (int i = 0; i < str.Length; i++) {
      char ch = str[i];
      if (Char.IsUpper(ch)) {
        x += Char.ToLower(ch);
      }
      else {
        x += Char.ToUpper(ch);
      }
    }
    Console.WriteLine(x);
  }
}
 
// This code is contributed by lokeshmvs21.


Javascript




// Javascript program to Convert characters
// of a string to opposite case
  
    let str = "GeEkSfOrGeEkS";
    let x = "";
    for (let i = 0; i < str.length; i++) {
      let ch = str[i];
      if(str.charAt(i) === str.charAt(i).toUpperCase())
        x += str.charAt(i).toLowerCase(ch);
      else
        x += str.charAt(i).toUpperCase(ch);
    }
    console.log(x);
     
    // This code is contributed by garg28harsh.


Output

gEeKsFoRgEeKs





Approach : Using index() method

C++




// C++ program to Convert characters
// of a string to opposite case
#include <iostream>
using namespace std;
 
int main()
{
    string str = "GeEkSfOrGeEkS";
    string x = "";
    string upperalphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string loweralphabets = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < str.length(); i++) {
        char ch = str[i];
        if (upperalphabets.find(ch) != -1) {
            x += loweralphabets[upperalphabets.find(ch)];
        }
        else {
            x += upperalphabets[loweralphabets.find(ch)];
        }
    }
    cout << x << endl;
    return 0;
}
// This code is contributed by Prajwal Kandekar


C




// C program to Convert characters
// of a string to opposite case
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[] = "GeEkSfOrGeEkS";
    char x[100] = "";
    char upperalphabets[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char loweralphabets[] = "abcdefghijklmnopqrstuvwxyz";
    int i, j;
    for (i = 0; i < strlen(str); i++) {
        char ch = str[i];
        if (strchr(upperalphabets, ch)) {
            j = strchr(upperalphabets, ch) - upperalphabets;
            x[i] = loweralphabets[j];
        }
        else {
            j = strchr(loweralphabets, ch) - loweralphabets;
            x[i] = upperalphabets[j];
        }
    }
    printf("%s\n", x);
    return 0;
}


Java




// Java program to Convert characters
// of a string to opposite case
 
public class GFG {
  public static void main(String[] args)
  {
    String str = "GeEkSfOrGeEkS";
    String x = "";
    String upperalphabets
      = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String loweralphabets
      = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < str.length(); i++) {
      char ch = str.charAt(i);
      if (upperalphabets.indexOf(ch) != -1) {
        x += loweralphabets.charAt(
          upperalphabets.indexOf(ch));
      }
      else {
        x += upperalphabets.charAt(
          loweralphabets.indexOf(ch));
      }
    }
    System.out.println(x);
  }
}
 
// This Code is contributed by karandeep1234


Python3




# Python3 program to Convert characters
# of a string to opposite case
 
str = "GeEkSfOrGeEkS"
x=""
upperalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
loweralphabets="abcdefghijklmnopqrstuvwxyz"
for i in str:
    if i in upperalphabets:
        x+=loweralphabets[upperalphabets.index(i)]
    else:
        x+=upperalphabets[loweralphabets.index(i)]
print(x)


C#




// C# program to Convert characters
// of a string to opposite case
using System;
 
public class GFG {
  public static void Main(string[] args)
  {
    string str = "GeEkSfOrGeEkS";
    string x = "";
    string upperalphabets
      = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string loweralphabets
      = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < str.Length; i++) {
      char ch = str[i];
      if (upperalphabets.IndexOf(ch) != -1) {
        x += loweralphabets[upperalphabets.IndexOf(
          ch)];
      }
      else {
        x += upperalphabets[loweralphabets.IndexOf(
          ch)];
      }
    }
    Console.WriteLine(x);
  }
}
 
// This Code is contributed by karandeep1234


Javascript




// Javascript program to Convert characters
// of a string to opposite case
 
 
    let str = "GeEkSfOrGeEkS";
    let x = "";
    let upperalphabets
      = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let loweralphabets
      = "abcdefghijklmnopqrstuvwxyz";
    for (let i = 0; i < str.length; i++) {
      let ch = str[i];
      if (upperalphabets.indexOf(ch) != -1) {
        x += loweralphabets[upperalphabets.indexOf(ch)];
      }
      else {
        x += upperalphabets[loweralphabets.indexOf(ch)];
      }
    }
    console.log(x);
 
// This code is contributed by garg28harsh.


Output

gEeKsFoRgEeKs





Another Approach:-

  • In this approach we will use transform function
  • What transform function do is that it convert the case of a string into upper case or lower case without using any other extra space or string.
  • In this approach we will just traverse the string and check the case of the character.
  • If the character is in upper case then we will use transform function to convert it into lower case.
  • else we will convert in into upper case
  • Below is the implementation of the above approach.

Implementation:-

C++




// C++ program to Convert characters
// of a string to opposite case
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str = "GeEkSfOrGeEkS";
    for (int i = 0; i < str.length(); i++) {
          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);
        }
    }
    cout << str << endl;
    return 0;
}
// This code is contributed by shubhamrajput6156


C




// C program to Convert characters
// of a string to opposite case
 
#include <ctype.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[] = "GeEkSfOrGeEkS";
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        if (isupper(str[i])) {
            str[i] = tolower(str[i]);
        }
        else {
            str[i] = toupper(str[i]);
        }
    }
    printf("%s\n", str);
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        String str = "GeEkSfOrGeEkS";
        StringBuilder sb = new StringBuilder(str);
         
        for (int i = 0; i < sb.length(); i++) {
            if (Character.isUpperCase(sb.charAt(i))) {
                sb.setCharAt(i, Character.toLowerCase(sb.charAt(i)));
            } else {
                sb.setCharAt(i, Character.toUpperCase(sb.charAt(i)));
            }
        }
         
        str = sb.toString();
        System.out.println(str);
    }
}


Python3




# Python program to Convert characters
# of a string to opposite case
 
str = "GeEkSfOrGeEkS"
 
for i in range(len(str)):
    if str[i].isupper():
        str = str[:i] + str[i].lower() + str[i+1:]
    else:
        str = str[:i] + str[i].upper() + str[i+1:]
 
print(str)


C#




// C# program to Convert characters
// of a string to opposite case
using System;
 
class GFG {
    public static void Main() {
        string str = "GeEkSfOrGeEkS";
      for (int i = 0; i < str.Length; i++) {
          // If the character is upper case, convert it to lower case
          if (Char.IsUpper(str[i])) {
          str = str.Remove(i, 1).Insert(i, Char.ToLower(str[i]).ToString());
      }
      // If the character is lower case, convert it to upper case
      else {
          str = str.Remove(i, 1).Insert(i, Char.ToUpper(str[i]).ToString());
      }
    }
    Console.WriteLine(str);
    }
}


Javascript




let str = "GeEkSfOrGeEkS";
for (let i = 0; i < str.length; i++) {
  if (str[i] === str[i].toUpperCase()) {
    str = str.slice(0, i) + str[i].toLowerCase() + str.slice(i + 1);
  } else {
    str = str.slice(0, i) + str[i].toUpperCase() + str.slice(i + 1);
  }
}
console.log(str);
 
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL


Output

gEeKsFoRgEeKs





Time Complexity:- O(N) Where N is length of String

Auxiliary Space:- O(1)

Another Approach:

In this implementation, we initialize a pointer p to the start of the string str. We then use a while loop to iterate through the string by checking if the character p points to is the null character (‘\0’). Inside the loop, we use the same logic as the previous implementation, but instead of accessing the array element at index i, we use the dereference operator * to access the value that p points to. After updating the character at the current position, we increment the pointer p to point to the next character in the string.

C++




#include <ctype.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[] = "GeEkSfOrGeEkS";
    char* p = str;  // initialize pointer to start of string
    while (*p != '\0') {
        if (isupper(*p)) {
            *p = tolower(*p);
        }
        else {
            *p = toupper(*p);
        }
        p++;  // move pointer to next character
    }
    printf("%s\n", str);
    return 0;
}


Java




import java.io.*;
public class GFG {
    public static void main(String[] args) {
        String str = "GeEkSfOrGeEkS";
        char[] charArray = str.toCharArray();
      // Convert the string to a character array
        for (int i = 0; i < charArray.length; i++) {
            if (Character.isUpperCase(charArray[i])) {
                charArray[i] = Character.toLowerCase(charArray[i]);
              // Convert uppercase to lowercase
            } else {
                charArray[i] = Character.toUpperCase(charArray[i]);
              // Convert lowercase to uppercase
            }
        }
        String toggledStr = new String(charArray);
      // Convert the character array back to  string
        System.out.println(toggledStr);
    }
}


Python3




str_value = "GeEkSfOrGeEkS"
p = 0  # Initialize an index variable to start of string
str_list = list(str_value)  # Convert the string to a list of characters
 
while p < len(str_list):
    if str_list[p].isupper():
        str_list[p] = str_list[p].lower()
    else:
        str_list[p] = str_list[p].upper()
    p += 1  # Move index to the next character
 
result = ''.join(str_list)  # Convert the list back to a string
print(result)
 
# This code is contributed by akshitaguprzj3


C#




using System;
 
class Program {
    static void Main(string[] args)
    {
        string str = "GeEkSfOrGeEkS";
        char[] charArray
            = str.ToCharArray(); // Convert the string to a
                                 // character array
 
        for (int i = 0; i < charArray.Length; i++) {
            if (char.IsUpper(
                    charArray[i])) // Check if the character
                                   // is uppercase
            {
                charArray[i] = char.ToLower(
                    charArray[i]); // Convert to lowercase
            }
            else {
                charArray[i] = char.ToUpper(
                    charArray[i]); // Convert to uppercase
            }
        }
 
        string modifiedStr = new string(
            charArray); // Convert the character array back
                        // to a string
        Console.WriteLine(modifiedStr);
    }
}


Javascript




// JavaScript Program for the above approach
const str = "GeEkSfOrGeEkS";
let result = "";
for (let i = 0; i < str.length; i++) {
  const char = str.charAt(i);
  if (char === char.toUpperCase()) {
      result += char.toLowerCase();
  } else {
      result += char.toUpperCase();
  }
}
console.log(result);
// THIS CODE IS CONTRIBUTED BY PIYUSH AGARWAL


Output

gEeKsFoRgEeKs






Time Complexity:- O(n) Where N is length of input String

Auxiliary Space:- O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads