我使用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()
一种方法。
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();
public static String capitalizer(final String texto) {
// split words
String[] palavras = texto.split(" ");
StringBuilder sb = new StringBuilder();
// list of word exceptions
List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));
for (String palavra : palavras) {
if (excessoes.contains(palavra.toLowerCase()))
sb.append(palavra.toLowerCase()).append(" ");
else
sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
}
return sb.toString().trim();
}