我使用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()
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();
}
您可以使用以下代码:
public static String capitalizeString(String string) {
if (string == null || string.trim().isEmpty()) {
return string;
}
char c[] = string.trim().toLowerCase().toCharArray();
c[0] = Character.toUpperCase(c[0]);
return new String(c);
}
使用JUnit的示例测试:
@Test
public void capitalizeStringUpperCaseTest() {
String string = "HELLO WORLD ";
string = capitalizeString(string);
assertThat(string, is("Hello world"));
}
@Test
public void capitalizeStringLowerCaseTest() {
String string = "hello world ";
string = capitalizeString(string);
assertThat(string, is("Hello world"));
}