我有一个类似于"Taxi or bus driver“的字符串列表。我需要将每个单词的第一个字母转换为大写字母,但单词"or“除外。有什么简单的方法可以使用Java流来实现这一点吗?我已经尝试了Pattern.compile.splitasstream技术,我不能连接所有拆分的令牌回形成原始字符串任何帮助将被appreciated.If任何人需要我可以在这里发布我的代码。
发布于 2018-05-31 08:35:37
下面是我的代码:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConvertToCapitalUsingStreams {
// collection holds all the words that are not to be capitalized
private static final List<String> EXCLUSION_LIST = Arrays.asList(new String[]{"or"});
public String convertToInitCase(final String data) {
String[] words = data.split("\\s+");
List<String> initUpperWords = Arrays.stream(words).map(word -> {
//first make it lowercase
return word.toLowerCase();
}).map(word -> {
//if word present in EXCLUSION_LIST return the words as is
if (EXCLUSION_LIST.contains(word)) {
return word;
}
//if the word not present in EXCLUSION_LIST, Change the case of
//first letter of the word and return
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}).collect(Collectors.toList());
// convert back the list of words into a single string
String finalWord = String.join(" ", initUpperWords);
return finalWord;
}
public static void main(String[] a) {
System.out.println(new ConvertToCapitalUsingStreams().convertToInitCase("Taxi or bus driver"));
}
}
注意:您可能还想看看这篇关于使用apache commons-text库来完成这项工作的SO文章。
发布于 2018-05-31 13:30:11
将字符串拆分为单词,然后将第一个字符转换为大写,然后将其joining
以形成原始字符串:
String input = "Taxi or bus driver";
String output = Stream.of(input.split(" "))
.map(w -> {
if (w.equals("or") || w.length() == 0) {
return w;
}
return w.substring(1) + Character.toUpperCase(w.charAt(0));
})
.collect(Collectors.joining(" "));
https://stackoverflow.com/questions/50614903
复制相似问题