我正在 Java 实验室工作,并已完成了操作最终用户输入的字符串的 7 项任务中的大约 5 项。然而,一个任务是将字符串的第一个单词更改为全部大写。我们只允许使用 String 类的方法(不允许使用 StringBuffer 和 StringBuilder),这使得这需要更多的手动操作。
将整个字符串转换为大写非常简单:
String upper = userInput.toUpperCase();
但只有部分字符串欺骗了我。
我正在考虑做一个 while 循环,其中每个字符串索引都转换为大写,直到循环到达“”。所以像这样:
String stringCapped = "";
String stringRemaining = "";
//get the string from the end-user
Scanner scan = new Scanner(System.in);
System.out.println("Please enter any string: ");
String userInput = scan.nextLine();
//find the length of the string
int stringLength = userInput.length();
while (userInput.charAt(charSearch) != ' '){
//Here I need to replace each char with an uppercase until I reach a space
//then add the remaining string.
stringCapped = userInput.toUpperCase(charAt(charSearch))... + stringRemaining;
charSearch = ++charSearch;
}
基本上“Hello World”需要变成“HELLO World”
请帮忙,谢谢!
最佳答案
你可以尝试这样的事情
// get the string from the end-user
Scanner scan = new Scanner(System.in);
System.out.println("Please enter any string: ");
String userInput = scan.nextLine();
// find the length of the string
int stringLength = userInput.length();
int firstWordEnd = userInput.indexOf(" ");
String firstWord = userInput.substring(0, firstWordEnd);
String newFirstWord = firstWord.toUpperCase();
System.out.println(userInput.replace(firstWord, newFirstWord));
关于java - 如何仅使用 String 类将字符串的第一个单词更改为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22059822/