将字符串分解为大写的字符 [英] Breaking Strings into chars that are in upper case

查看:92
本文介绍了将字符串分解为大写的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个方法来读取整个类代码并用它做一些事情。

I'm making a method to read a whole class code and do some stuff with it.

我想要做的是获取方法的名称,用它做一个字符串。

What I want to do is get the name of the method, and make a String with it.

类似removeProduct

Something like removeProduct

我将制作一个字符串删除产品

如何在大写情况下拆分名称方法?
如何构建这个新字符串,每个单词的第一个字母作为大写字母?
我正在使用子字符串,有没有更容易和更好的方法呢?

How can I split the name method in capital cases? How can I build this new string with the first letter of each word as capital case? I'm doing it with substring, is there a easier and better way to do it?

ps:我确定我的巴西英语没有标题帮助。如果有人能让它看起来更好,我会很感激。

ps: I'm sure my brazilian English didn't help on title. If anyone can make it looks better, I'd appreciate.

推荐答案

您可以使用正则表达式将名称拆分为各种单词,然后大写第一个:

You can use a regular expression to split the name into the various words, and then capitalize the first one:

public static void main(String[] args) {
    String input = "removeProduct";

    //split into words
    String[] words = input.split("(?=[A-Z])");

    words[0] = capitalizeFirstLetter(words[0]);

    //join
    StringBuilder builder = new StringBuilder();
    for ( String s : words ) {
        builder.append(s).append(" ");
    }

    System.out.println(builder.toString());

}

private static String capitalizeFirstLetter(String in) {
    return in.substring(0, 1).toUpperCase() + in.substring(1);
}

请注意,这需要更好的角落案件处理,例如不要在结束并处理1个字符。

Note that this needs better corner case handling, such as not appending a space at the end and handling 1-char words.

编辑:我的意思是解释正则表达式。正则表达式(?= [AZ])零宽度断言(正向前瞻)匹配下一个字符位于A和Z之间的位置。

Edit: I meant to explain the regex. The regular expression (?=[A-Z]) is a zero-width assertion (positive lookahead) matching a position where the next character is between 'A' and 'Z'.

这篇关于将字符串分解为大写的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆