给定一个字符串,编写一个函数,该函数使用适当的按位运算运算符返回字符串的切换大小写。
在ASCII码中,字符“ A”是整数65 =(0100 0001)2,而字符“ a”是整数97 =(0110 0001)2。同样,字符“ D”是整数68 =(0100 0100)2,而字符“ d”是整数100 =(0110 0100)2。
如我们所见,ASCII码“ A”和“ a”中只有第六个最低有效位有所不同。在“ D”和“ d”的ASCII代码中可以看到类似的行为。因此,我们需要切换此位以切换大小写。
例子:
Input : "GeekSfOrgEEKs"
Output : "gEEKsFoRGeekS"
Input : "StRinG"
Output : "sTrINg"
ASCII表的构造方式使得小写字母的二进制表示形式与大写字母的二进制表示形式几乎相同。
切换案例
第六个LSB为1的整数是32(0010 0000)。因此,具有32个字符的按位异或将切换字符的第六LSB,因此,会切换其情况。如果字符是大写,它将被转换为小写,反之亦然。
C
// C program to get toggle case of a string
#include
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
char *toggleCase(char *a)
{
for (int i=0; a[i]!='\0'; i++) {
// Bitwise EXOR with 32
a[i] ^= 32;
}
return a;
}
// Driver Code
int main()
{
char str[] = "CheRrY";
printf("Toggle case: %s\n", toggleCase(str));
printf("Original string: %s", toggleCase(str));
return 0;
}
Java
// program to get toggle case of a string
public class Test
{
static int x=32;
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
static String toggleCase(char[] a)
{
for (int i=0; i
Python3
# Python3 program to get toggle case of a string
x = 32;
# tOGGLE cASE = swaps CAPS to lower
# case and lower case to CAPS
def toggleCase(a):
for i in range(len(a)):
# Bitwise EXOR with 32
a = a[:i] + chr(ord(a[i]) ^ 32) + a[i + 1:];
return a;
# Driver Code
str = "CheRrY";
print("Toggle case: ", end = "");
str = toggleCase(str);
print(str);
print("Original string: ", end = "");
str = toggleCase(str);
print(str);
# This code is contributed by 29AjayKumar
C#
// C# program to get toggle case of a string
using System;
class GFG {
// tOGGLE cASE = swaps CAPS to lower
// case and lower case to CAPS
static string toggleCase(char []a)
{
for (int i = 0; i < a.Length; i++)
{
// Bitwise EXOR with 32
a[i] ^= (char)32;
}
return new string(a);
}
/* Driver program */
public static void Main()
{
string str = "CheRrY";
Console.Write("Toggle case: ");
str = toggleCase(str.ToCharArray());
Console.WriteLine(str);
Console.Write("Original string: ");
str = toggleCase(str.ToCharArray());
Console.Write(str);
}
}
// This code is contributed by nitin mittal.
Javascript
输出:
Toggle case: cHErRy
Original string: CheRrY