[Programmers / JAVA] Level 1 Making Strange Text (12930)
[Programmers / JAVA] Level 1 Making Strange Text (12930)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
A string s consists of one or more words. Each word is separated by one or more whitespace characters. Complete the function solution, which returns a string in which the even-indexed letters of each word are converted to uppercase and the odd-indexed letters are converted to lowercase.
- The even/odd index must be determined per word (split by whitespace), not across the entire string.
- The first letter is treated as index 0, i.e., an even-indexed letter.
| s | return |
|---|---|
| "try hello world" | "TrY HeLlO WoRlD" |
"try hello world" consists of three words: "try", "hello", and "world". Converting the even-indexed letters of each word to uppercase and the odd-indexed letters to lowercase gives "TrY", "HeLlO", and "WoRlD". Therefore it returns "TrY HeLlO WoRlD".
Split the characters by word, and replace odd-indexed characters with lowercase and even-indexed characters with uppercase, then return the result.
Since the conversion needs to be done per word rather than across the whole string, split the string by whitespace and perform the case conversion accordingly.
Split s into individual characters and loop through them, comparing the character index to determine the case. When a space is encountered, reset the index.
JAVA
/** * Making Strange Text class * * @author RWB * @since 2021.12.13 Mon 18:03:00 */ class Solution { /** * Method that returns the answer * * @param s: [String] string * * @return [String] answer */ public String solution(String s) { String[] answer = s.split(""); int index = 0; for (int i = 0; i < answer.length; i++) { // If it's a space if (answer[i].equals(" ")) { index = 0; answer[i] = " "; } // If it's a character else { // If it's an even index if (index % 2 == 0) { answer[i] = answer[i].toUpperCase(); } // If it's an odd index else { answer[i] = answer[i].toLowerCase(); } index++; } } return String.join("", answer); } }
