java - 将 String 的首字母分开以进行大写

标签 java string split capitalization

我想从用户那里获取一个字符串输入,并对其进行格式化,使第一个字母大写,其余字母不大写。我想通过拆分字符串中的第一个字母并在其上使用 .toUpperCase() 并在其余部分上使用 .toLowerCase() 来做到这一点,然后合并它们回到一起。

我有一个想法,但不能解决所有问题:

userInput = input.nextLine();
String firstLetter = ???
firstLetter.toUpperCase();
restOfString.toLowerCase();
String merged = firstLetter + restOfString;

这似乎不起作用:

            name = input.nextLine();
            firstLetter = name.substring(0,1);
            remainingString = name.substring(1);
            firstLetter.toUpperCase();
            remainingString.toLowerCase();
            name = firstLetter + remainingString;

最佳答案

您可以使用子字符串。

String firstLetter = userInput.substring(0,1); //takes first letter
String restOfString = userInput.substring(1); //takes rest of sentence
firstLetter = firstLetter.toUpperCase(); //make sure to set the string, the methods return strings, they don't change the string itself
restOfString = restOfString.toLowerCase();
String merged = firstletter + restOfString;

编辑:如果您希望对用户的输入进行错误检查:

if(userInput.length < 2) {
    throw new InputMismatchException("Sentence too short to properly capitalize!";
}

关于java - 将 String 的首字母分开以进行大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26536182/

相关文章:

javascript - 查找数组中最长的字符串

arrays - 将函数拆分为数组。类型不匹配错误#13

python - 如果出现子字符串,则拆分字符串

javascript - 如何将一个字符串拆分为多个 html 文本字段

java - 从 Spring 表单获取 Post 请求中的 null 设置值

java - H2:JdbcSQLException:此 CLOB 或 BLOB 引用超时

java - 如何使用json将包含多个对象的json文件转换为java对象列表

java - 设置 <String> 在应用程序重新启动后从 SharedPreferences 恢复时丢失数据

java - 替换字符串从 <\开始

Ruby - 删除部分文本