Learn-dsa..in 30 days!



























CC-18 : Toggle case of characters of String.

Description:

Given input String str, toggle the case of characters ie. convert the lowercase characters to upper case and vice versa.

Test cases and expected outputs:

Input Parameters Expected outputs
str="aBc"; AbC
str="XyZ" xYz

Pseudocode:

The java method should accept following input parameters: str (String).
Initialize char array chars=str.toCharArray().
Initialize StringBuilder sb. We will use this variable to assemble the new String with character case toggled.
Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
When we do ((int) 'A'-'a' ) we get the difference in byte value of the 2 characters. We will use this difference to toggle all the characters between lowercase and upper case. Lowercase characters can be converted to upper case by adding above difference to the lowercase characters.
Similarly, uppercase characters can be converted to lower case by adding difference of ((int)‘a’ – ‘A’)to the uppercase characters.
When above loop is completed, chars contains the toggled case characters. Use String builder to create a String from chars. Return the new String with toggle characters from the program.

Code:

public String stringToggle(String str) {
	char[] chars=str.toCharArray();
	StringBuilder sb=new StringBuilder();
	for (int idx=0; idx < chars.length; idx++) {
		if (chars[idx] >= 'a' && chars[idx] <= 'z') {
			System.out.println(chars[idx]+" "+ (int)( 'A'-'a'));
			chars[idx]=(char) (chars[idx]+ 'A'-'a');
		}else if (chars[idx] >= 'A'  && chars[idx] <= 'Z') {
			System.out.println(chars[idx]+" "+ (int)( 'A'-'a'));
			chars[idx]=(char) (chars[idx]+'a'-'A');
		}
	}
	sb.append(chars);
	return sb.toString();
}

Click here to download and run code and test cases !