Python Program for Convert characters of a string to opposite case
Given a string, convert the characters of the string into opposite case,i.e. if a character is 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:
- Take one string of any length and calculate its length.
- 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 in upper case, else add 32 to convert it in lower case
- Print the final string.
Implementation:
Python3
|
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
- Si ^ (1 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:
Python3
|
String after toggle gEkF@RgEEK$
Time Complexity: O(n)
Python3
|
Please refer complete article on Convert characters of a string to opposite case for more details!
Given a string, convert the characters of the string into opposite case,i.e. if a character is 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:
- Take one string of any length and calculate its length.
- 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 in upper case, else add 32 to convert it in lower case
- Print the final string.
Implementation:
Python3
|
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
- Si ^ (1 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:
Python3
|
String after toggle gEkF@RgEEK$
Time Complexity: O(n)
Python3
|
Please refer complete article on Convert characters of a string to opposite case for more details!