📌  相关文章
📜  将字符的字符串转换为相反的大小写

📅  最后修改于: 2022-05-13 01:57:06.709000             🧑  作者: Mango

将字符的字符串转换为相反的大小写

给定一个字符串,将字符串的字符转换为相反的大小写,即如果一个字符是小写,则将其转换为大写,反之亦然。

例子:

Input : geeksForgEeks
Output : GEEKSfORGeEKS

Input : hello every one
Output : HELLO EVERY ONE

字母的 ASCII 值:A – Z = 65 到 90,a – z = 97 到 122
脚步:

  1. 取一个任意长度的字符串并计算它的长度。
  2. 字符字符字符串并继续检查索引。
    • 如果索引中的字符是小写,则减去 32 将其转换为大写,否则加 32 将其转换为小写
  3. 打印最后的字符串。
C++
// CPP program to Convert characters
// of a string to opposite case
#include 
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;
}


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)
 
        else if 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='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


C++
// C++ program to toggle all characters
#include
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


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

 
// This code is contributed by Akshit Saxena


输出
gEeKsFoRgEeKs

时间复杂度:O(n)
注意:这个程序也可以使用 C++ 内置函数来完成——Character .toLowerCase(char) 和字符 字符(char)。

方法2:可以使用字母大小写切换来解决问题。请按照以下步骤解决问题:

  • 遍历给定的字符串S。
  • 对于每个字符S i ,做S i = S i ^ (1 << 5)。
  • 西_ ^ (1 << 5)切换第5 位,这意味着97将变为65 ,而65将变为97:
    • 65 ^ 32 = 97
    • 97 ^ 32 = 65
  • 在所有操作后打印字符串

下面是上述方法的实现:

C++

// C++ program to toggle all characters
#include
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

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


 
// This code is contributed by Akshit Saxena