#81 Format words into a sentence
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed into the method should result in an empty string being returned.
Kata.formatWords(new String[] {"ninja", "samurai", "ronin"}) => "ninja, samurai and ronin"
Kata.formatWords(new String[] {"ninja", "", "ronin"}) => "ninja and ronin"
Kata.formatWords(new String[] {}) => ""
import java.util.Arrays; import java.util.stream.Collectors; public class Kata { public static String replaceLast(String str, String regex, String replacement) { int regexIndexOf = str.lastIndexOf(regex); if(regexIndexOf == -1){ return str; }else{ return str.substring(0, regexIndexOf) + replacement + str.substring(regexIndexOf + regex.length()); } } public static String formatWords(String[] words) { // Do the things... if(words == null) return ""; return replaceLast(Arrays.stream(words).filter(word -> !word.equals("")).collect(Collectors.joining(", ")),", "," and "); } }
'매일매일개발 > Codewars' 카테고리의 다른 글
codewars #83 Stop gninnipS My sdroW! (6kyu) (0) | 2018.07.23 |
---|---|
codewars #82Evil Autocorrect Prank (6kyu) (0) | 2018.07.19 |
codewars #80 Calculating Batting Average (6kyu) (0) | 2018.07.17 |
codewars #79 Human readable duration format (4kyu) (0) | 2018.07.13 |
codewars #78 Convert PascalCase string into snake_case (5kyu) (0) | 2018.07.12 |