The Wayback Machine - https://web.archive.org/web/20240913100525/https://www.geeksforgeeks.org/convert-alternate-characters-string-upper-case/
Open In App

Convert characters of a string to opposite case

Last Updated : 17 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
75.27%
72.6K

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)



Similar Reads

Minimum number of operations to move all uppercase characters before all lower case characters
Given a string str, containing upper case and lower case characters. In a single operations, any lowercase character can be converted to an uppercase character and vice versa. The task is to print the minimum number of such operations required so that the resultant string consists of zero or more upper case characters followed by zero or more lower
8 min read
Check whether the given character is in upper case, lower case or non alphabetic character
Given a character, the task is to check whether the given character is in upper case, lower case, or non-alphabetic character Examples: Input: ch = 'A'Output: A is an UpperCase characterInput: ch = 'a'Output: a is an LowerCase characterInput: ch = '0'Output: 0 is not an alphabetic characterApproach: The key to solving this problem lies in the ASCII
11 min read
Lower case to upper case - An interesting fact
Problem: Given a string containing only lowercase letters, generate a string with the same letters, but in uppercase. Input : GeeksForGeeks Output : GEEKSFORGEEKS Recommended PracticeLower case to upper caseTry It! The first method that comes to our mind is C/C++ Code // C++ program to convert a string to uppercase #include &lt;iostream&gt; using n
7 min read
Count of camel case characters present in a given string
Given a string S, the task is to count the number of camel case characters present in the given string. The camel case character is defined as the number of uppercase characters in the given string. Examples: Input: S = "ckjkUUYII"Output: 5Explanation: Camel case characters present are U, U, Y, I and I. Input: S = "abcd"Output: 0 Recommended: Pleas
7 min read
Position of a person diametrically opposite on a circle
There are n people standing on the circumference of a circle. Given the position of a person m, the task is to find the position of the person standing diametrically opposite to m on the circle. Examples: Input: n = 6, m = 2 Output: 5 Position 5 is opposite to 2 when there are 6 positions in total Input: n = 8, m = 5 Output: 1 Approach: There are t
3 min read
Time until distance gets equal to X between two objects moving in opposite direction
Consider two people moving in opposite direction with speeds U meters/second and V meters/second respectively. The task is to find how long will take to make the distance between them X meters.Examples: Input: U = 3, V = 3, X = 3 Output: 0.5 After 0.5 seconds, policeman A will be at distance 1.5 meters and policeman B will be at distance 1.5 meters
4 min read
Exterior angle of a cyclic quadrilateral when the opposite interior angle is given
Given cyclic quadrilateral inside a circle, the task is to find the exterior angle of the cyclic quadrilateral when the opposite interior angle is given.Examples: Input: 48 Output: 48 degrees Input: 83 Output: 83 degrees Approach: Let, the exterior angle, angle CDE = xand, it's opposite interior angle is angle ABCas, ADE is a straight lineso, angle
3 min read
Find two vertices of an isosceles triangle in which there is rectangle with opposite corners (0, 0) and (X, Y)
Given two integers X and Y. The task is to find two vertices of an isosceles triangle ABC(right-angled at B) which has one vertex at a point B(0, 0). And there is a rectangle with opposite sides (0, 0) and (X, Y). All the points of this rectangle are located inside or on the border of the triangle. Print 4 integers x1, y1, x2, y2, where A(x1, y1) a
5 min read
Number of ways to arrange 2*N persons on the two sides of a table with X and Y persons on opposite sides
Given three integers N, X and Y. The task is to find the number of ways to arrange 2*N persons along two sides of a table with N number of chairs on each side such that X persons are on one side and Y persons are on the opposite side. Note: Both X and Y are less than or equals to N.Examples: Input : N = 5, X = 4, Y = 2 Output : 57600 Explanation :
9 min read
Check if roots of a Quadratic Equation are numerically equal but opposite in sign or not
Given the coefficients (constants) of a quadratic equation [Tex]ax^{2} + bx + c=0 [/Tex], i.e. a, b, and c; the task is to check whether roots of the equation represented by these constants are numerically equal but opposite in sign or not.Examples: Input: a = 2, b = 0, c = -1 Output: Yes Explanation: The given quadratic equation is [Tex]2x^{2}-2=0
3 min read
Find the vertex diagonally opposite to the vertex M from an N-sided polygon
Given two integers N and M, the task is to find the vertex diagonally opposite to the Mth vertex of an N-sided polygon. Examples: Input: N = 6, M = 2 Output: 5 Explanation: It can be observed from the image above that the vertex opposite to vertex 5 is 2. Input: N = 8, M = 5 Output: 1 Explanation: It can be observed from the image above that the ve
3 min read
Minimum number of jumps to obtain an element of opposite parity
Given two arrays arr[] and jumps[] consisting of N positive integers, the task for each array element arr[i] is to find the minimum number of jumps required to reach an element of opposite parity. The only possible jumps from any array element arr[i] are (i + jumps[i]) or (i - jumps[i]). Examples: Input: arr[] = {4, 2, 5, 2, 1}, jumps[] = {1, 2, 3,
14 min read
Sum of nodes having sum of subtrees of opposite parities
Given a Binary Tree, the task is to find the sum of all such nodes from the given tree whose sum of left and right subtree is either odd and even or even and odd respectively. Examples: Input: 11 / \ 23 44 / \ / \ 13 9 22 7 / \ 6 15Output: 33Explanation: There are only two such nodes: Node 22 having left subtree and right subtree sum as 6 (even) an
8 min read
Area of a triangle with two vertices at midpoints of opposite sides of a square and the other vertex lying on vertex of a square
Given a positive integer N representing the side of a square, the task is to find the area of a triangle formed by connecting the midpoints of two adjacent sides and vertex opposite to the two sides. Examples: Input: N = 10Output: 37.5 Input: N = 1Output: 0.375 Approach: The given problem can be solved based on the following observations: The one s
5 min read
Find all pairwise sum possible using elements at opposite ends with minimum replacements
Given an array arr[] of even length N and an integer K denoting the range of numbers in the array i.e. the numbers in the array are in the range [1, K]. The task is to find all opposite indices pair sums possible with minimum replacements where in any replacement any number of the array can be changed to any other number in the range [1, K]. Note:
7 min read
Check if array can be sorted by swapping adjacent elements of opposite parity
Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times. Examples: Input : n = 4, A = [1, 6, 51, 16]Output: YESExplanation: Since 51 is odd and 16 is even, we will jus
9 min read
Reduce Array by replacing adjacent opposite sign pairs with their absolute maximum
Given an array arr[] of size N, the task is to find the final array by repeatedly performing the following operations if two elements of opposite signs are adjacent: Remove both opposite signed elements from the array and insert the element having maximum absolute value along with its sign.If both the elements have the same absolute value, both wil
9 min read
Minimum operations to make Array distinct by deleting and appending on opposite ends
Given an array arr[] of N integers. the task is to find the minimum number of operations required to make all the elements of the array distinct using the following operations. Remove one element from the starting of the array arr[] and append any integer to the end.Remove one element from the end of the array arr[] and prepend any integer to the b
9 min read
Detect if two integers have opposite signs
Given two signed integers, write a function that returns true if the signs of given integers are different, otherwise false. For example, the function should return true -1 and +100, and should return false for -100 and -200. The function should not use any of the arithmetic operators. Let the given integers be x and y. The sign bit is 1 in negativ
8 min read
Understanding Opposite Polarity Concept in Binary Search
Opposite Polarity is a concept in Binary Search which works on the search space with the condition that the before and after regions of the search space will be reversed when the Binary Search Algorithm is applied to it. In this post, we will understand how the Opposite polarity concept in Binary Search works with the help of a problem. What is the
4 min read
The sum of opposite angles of a cyclic quadrilateral is 180° | Class 9 Maths Theorem
In Euclidean geometry, a cyclic quadrilateral or inscribed quadrilateral is a quadrilateral whose vertices all lie on a single circle. This circle is called the circumcircle or circumscribed circle, and the vertices are said to be concyclic. The center of the circle and its radius are called the circumcenter and the circumradius respectively. Other
6 min read
Convert vowels into upper case character in a given string
Given string str, the task is to convert all the vowels present in the given string to uppercase characters in the given string. Examples: Input: str = “GeeksforGeeks”Output: GEEksfOrGEEksExplanation:Vowels present in the given string are: {'e', 'o'}Replace 'e' to 'E' and 'o' to 'O'.Therefore, the required output is GEEksfOrGEEks. Input: str = “eut
7 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Check if a string can be made palindromic by swapping pairs of characters from indices having unequal characters in a Binary String
Given a string S and a binary string B, both of length N, the task is to check if the given string S can be made palindromic by repeatedly swapping characters at any pair of indices consisting of unequal characters in the string B. Examples: Input: S = "BAA", B = "100"Output: YesExplanation:Swapping S[0] and S[1] modifies S to "ABA" and B to "010".
15+ min read
Convert characters of string1 to characters present in string2 by incrementing or decrementing lexicographically
Given two strings A and B having lower case English alphabets, the task is to find the number of operations required to convert string A such that it only contains letters that are also in the string B where at each operation, the current character can be changed to either the next character or the previous character. Also, the next character after
8 min read
Python | Toggle characters in words having same case
Given a string, toggle the characters of those words who have all their characters in the same case. Examples: Input : Geeks for Geeks Output : Geeks FOR Geeks Explanation: The string contains three words "Geeks", "for", "Geeks" out of which the word "for" contains all its characters as lower cases, therefore, toggle the case of the word. Print the
4 min read
Test Case Generation | Set 2 ( Random Characters, Strings and Arrays of Random Strings)
Set 1 (Random Numbers, Arrays and Matrices) Generating Random Characters C/C++ Code // A C++ Program to generate test cases for // random characters #include&lt;bits/stdc++.h&gt; using namespace std; // Define the number of runs for the test data // generated #define RUN 5 // Define the range of the test data generated // Here it is 'a' to 'z' #def
11 min read
Convert given Array of Strings to a Camel Case format sentence
Given an array arr[] of N strings, each containing words with upper or lower case English alphabets, the task is to create a sentence in a Camel Case format using them. Example: Input: arr[] = {"AnNiruddHA Routh", "LOVES", "to", "COdE everyDAY""}Output: AniruddhaRouth Loves To Code EverydayExplanation: The above sentence is the merged sentence of a
7 min read
Permutation of a string with maximum number of characters greater than its adjacent characters
Given a string str, the task is to print the maximum count of characters which are greater than both its left and right character in any permutation of the string. Examples: Input: str = "abc" Output: 1 Permutations of the string with the count of maximal character in each string are: abc - 0 acb - 1 Here a &lt; c &gt; b bac - 0 bca - 1 Here b &lt;
11 min read
Practice Tags :