首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用java 8流转换为大写字母

使用java 8流转换为大写字母
EN

Stack Overflow用户
提问于 2018-05-31 08:04:22
回答 2查看 7.7K关注 0票数 1

我有一个类似于"Taxi or bus driver“的字符串列表。我需要将每个单词的第一个字母转换为大写字母,但单词"or“除外。有什么简单的方法可以使用Java流来实现这一点吗?我已经尝试了Pattern.compile.splitasstream技术,我不能连接所有拆分的令牌回形成原始字符串任何帮助将被appreciated.If任何人需要我可以在这里发布我的代码。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-31 08:35:37

下面是我的代码:

代码语言:javascript
复制
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文章。

票数 2
EN

Stack Overflow用户

发布于 2018-05-31 13:30:11

将字符串拆分为单词,然后将第一个字符转换为大写,然后将其joining以形成原始字符串:

代码语言:javascript
复制
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(" "));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50614903

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档