在Java中转换为大写和小写 [英] Converting to upper and lower case in Java

查看:1014
本文介绍了在Java中转换为大写和小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串的第一个字符转换为大写字母,其余字符转换为小写字母。我该怎么做?

I want to convert the first character of a string to Uppercase and the rest of the characters to lowercase. How can I do it?

示例:

String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"


推荐答案

试试这个尺寸:

String properCase (String inputVal) {
    // Empty strings should be returned as-is.

    if (inputVal.length() == 0) return "";

    // Strings with only one character uppercased.

    if (inputVal.length() == 1) return inputVal.toUpperCase();

    // Otherwise uppercase first letter, lowercase the rest.

    return inputVal.substring(0,1).toUpperCase()
        + inputVal.substring(1).toLowerCase();
}

它基本上处理空字符串和单字符字符串的特殊情况否则是一个两位以上的字符串。并且,正如评论中所指出的,功能不需要单字符特殊情况,但我仍然喜欢明确,特别是如果它导致更少的无用调用,例如子字符串以获得空字符串,更低的外壳它,然后附加它。

It basically handles special cases of empty and one-character string first and correctly cases a two-plus-character string otherwise. And, as pointed out in a comment, the one-character special case isn't needed for functionality but I still prefer to be explicit, especially if it results in fewer useless calls, such as substring to get an empty string, lower-casing it, then appending it as well.

这篇关于在Java中转换为大写和小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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