我使用Java从用户获得一个字符串输入。我试着让输入的第一个字母大写。

我试了一下:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

这导致了以下编译错误:

类型不匹配:不能从InputStreamReader转换为BufferedReader 不能在基本类型char上调用toUppercase()


当前回答

在Android Studio中

将此依赖项添加到构建中。gradle(模块:app)

dependencies {
    ...
    compile 'org.apache.commons:commons-lang3:3.1'
    ...
}

现在你可以使用

String string = "STRING WITH ALL CAPPS AND SPACES";

string = string.toLowerCase(); // Make all lowercase if you have caps

someTextView.setText(WordUtils.capitalize(string));

其他回答

最短的:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

为我工作。

下面的解决方案将工作。

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

你不能在原始字符上使用toUpperCase(),但你可以先将整个String变成大写,然后取第一个字符,然后像上面所示的那样追加到子字符串。

给出的答案是只大写一个单词的第一个字母。使用以下代码将整个字符串大写。

public static void main(String[] args) {
    String str = "this is a random string";
    StringBuilder capitalizedString = new StringBuilder();
    String[] splited = str.trim().split("\\s+");

    for (String string : splited) {         
        String s1 = string.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + string.substring(1);

        capitalizedString.append(nameCapitalized);
        capitalizedString.append(" ");
    }
    System.out.println(capitalizedString.toString().trim());
}

输出: 这是一个随机字符串

一种方法。

String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
    return "";
}

char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;

此方法的缺点是,如果inputString很长,则将有三个这样长度的对象。和你一样

String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;

甚至

//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();

试试这个

这个方法做的是,考虑单词“hello world”这个方法把它变成“hello world”每个单词的开头大写。

 private String capitalizer(String word){

        String[] words = word.split(" ");
        StringBuilder sb = new StringBuilder();
        if (words[0].length() > 0) {
            sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
            for (int i = 1; i < words.length; i++) {
                sb.append(" ");
                sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
            }
        }
        return  sb.toString();

    }