我尝试创建一种方法,该方法接受字符串数组并返回单个格式化的字符串。 最后一个单词应以单词“ and”(而不是逗号)分隔。
但是它没有按预期工作:) 它不会用单词“和”代替最后一个逗号。 您能告诉我我的错误在哪里吗?
谢谢。
public class Kata {
public static String formatWords(String[] words) {
List<String> words1 = Arrays.asList(words);
ListIterator<String> wordIter = words1.listIterator();
StringBuilder out = new StringBuilder();
while (wordIter.hasNext()) {
out.append(wordIter.next());
if (wordIter.hasNext()) {
out.append(",");
}
}
return out.toString().replaceAll(",$", "and");
}
}
答案 0 :(得分:0)
我要迭代到前一个元素,然后用逗号将字符串连接起来,然后用“ and”将最后一个字符串连接起来:
public static String formatWords(String[] words) {
// Handle nulls and empty arrays
if (words == null || words.length) {
return "";
}
// Handle the first word
StringBuilder sb = new StringBuilder(words[0]);
// Handle all the words from the second to the before last
for (int i = 1; i < words.lengh - 1; ++i) {
sb.append(", ").append(word[i]);
}
// Check that there are at least two words
if (words.length > 1) {
// Handle the last word with an "and"
sb.append(" and ").append(words[1])
}
}
答案 1 :(得分:0)
replaceAll(",$", "and");
并没有您的想法。它找不到字符串中的最后一个,
。
尝试一下
while(wordIter.hasNext()) {
//your code
}
if (words.length > 1) {
int indexOfLastComma = out.length() - words[words.length - 1].length();
return out.replace(indexOfLastComma - 1, indexOfLastComma, " and ").toString();
}
return out.toString();
我们找到最后一个逗号的索引,然后将其替换为and
。
这是使用Streams的一种有趣方式
String tempResult = IntStream.range(0, words.length - 1)
.mapToObj(i -> words[i])
.collect(Collectors.joining(","));
return words.length > 1 ? tempResult + " and " + words[words.length - 1] : words[0];
编辑:
要过滤出空词,可以使用过滤器。现在,最后检查words.length > 1
将不再起作用(因为它可以包含空字符串)。因此,我正在检查tempResult
是否至少有一个,
。
这是一个完整的解决方案
String tempResult = Arrays.stream(words)
.filter(word -> !word.isEmpty())
.collect(Collectors.joining(","));
int indexOfLastComma = tempResult.lastIndexOf(',');
return indexOfLastComma != -1 ? tempResult.substring(0, indexOfLastComma) + " and "
+ tempResult.substring(indexOfLastComma + 1): tempResult;
它创建子字符串-因此不是最有效的解决方案。
答案 2 :(得分:0)
由于您可能有空项目,请先使用列表清除空项目:
public static String formatWords(String[] words) {
if (words == null)
return "";
List<String> list = new ArrayList<>();
for (String word : words) {
word = word.trim();
if (!word.isEmpty())
list.add(word);
}
StringBuilder out = new StringBuilder();
int len = list.size();
for (int i = 0; i < len; i++) {
out.append(list.get(i));
if (i == len - 2)
out.append(" and ");
else if (i < len - 2)
out.append(",");
}
return out.toString();
}
public static void main(String[] args) {
String[] array = {"", "apples", "", "oranges", "", "melons", ""};
System.out.println(formatWords(array));
}
将打印:
apples,oranges and melons
答案 3 :(得分:0)
您不需要使用List和ListIterator(在这种情况下!) 这是我的解决方案!
ps:我不明白为什么该方法是静态的,我认为在此Casa中是不必要的,因为我们不处理任何静态变量。
public static String formatWords(String[]words){
//Usefull to build the final resoult
StringBuilder sb = new StringBuilder();
/*start to put the word in the string builder
from the first to the last*/
for (int i = 0; i < words.length; i++) {
//put the wordat position i in string builder
sb.append(words[i]);
/*if the word is the 2 last and there are egual or more than
2 elements in words array
we can add the "and"*/
if(i==words.length-2 && words.length>=2) {
sb.append(" and ");
/*if the word is not the last put a comma
(actually we put a comma when there are more thand 3 item in words, but not in the last)
*/
}else if(i<words.length-1 ){
sb.append(", ");
}
/*if word[i] is the last of the array words we don't use nobody of the if!*/
/*this code word on 0 1,2,3 ore more word in array words!*/
}
return sb.toString();
}