Swap Case Coderbyte Solution

0

Have the function SwapCase(str) take the str parameter and swap the case of each character. 

For example: if str is "Hello World" the output should be hELLO wORLD. Let numbers and symbols stay the way they are.

swap case in java Coderbyte


import java.util.Scanner;



public class SwapCase {
final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
final String LOWER = UPPER.toLowerCase();

String SwapCase(String str) {
StringBuilder result = new StringBuilder("");

for (char c : str.toCharArray()) {
int index = UPPER.indexOf(c);
if (index != -1) {
result.append(LOWER.charAt(index));
} else {
index = LOWER.indexOf(c);

if (index != -1) {
result.append(UPPER.charAt(index));
} else {
result.append(c);
}
}
}

return result.toString();
}

public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
SwapCase c = new SwapCase();
System.out.print(c.SwapCase(s.nextLine()));
}
}

swap case in javascript

Using the JavaScript language, have the function SwapCase(str) take the str parameter and swap the case of each character. 

For example: if str is "Hello World" the output should be hELLO wORLD. Let numbers and symbols stay the way they are.


function SwapCase(str) {

var result = '';

for (var i = 0; i < str.length; i++) {
var c = str[i];
var u = c.toUpperCase();

result += u === c ? c.toLowerCase() : u;
}

return result;
}


Explanation

I am going to be using a new string to store my modified results. I am going to loop thru every character and covert it to UpperCase. Then I am going to compare that to the character in the string. If they are the same - meaning both are uppercase then I am going to return the lowercase of the character. If they are not the same then return the Uppercase character.

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !