我正在开发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”
请帮助,谢谢!
答案 0 :(得分:1)
您可以尝试这样的事情
// 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));
答案 1 :(得分:0)
尝试:
int spaceIndex = userInput.indexOf(' ');
String upper = userInput.split(0, spaceIndex).toUpperCase() + userInput.split(spaceIndex);
答案 2 :(得分:0)
尝试:
String orginal = "asdasd asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf ";
System.out.println(orginal);
String firstWord = orginal.substring(0, orginal.indexOf(' '));
System.out.println(orginal.replace(firstWord, firstWord.toUpperCase()));
结果:
asdasd asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf
ASDASD asda sdasdojk kjsdhfk hsdjfhdjs fhdsjf jhdf
答案 3 :(得分:0)
设s是你的字符串然后是字符串(s.charAt(0))。toUppercase()。concat(s.substring(1))应该这样做。没试过自己。如果不起作用,你可以在这里查看(http://docs.oracle.com/javase/6/docs/api/java/lang/String.html)。
答案 4 :(得分:0)
获胜者是:
String userInput = "abc def abc nbc wral abc def nbc abc";
String[] words = userInput.split(" ", 2); // split in 2 parts
System.out.println(words[0].toUpperCase() + " " + words[1]);
这是输出:
ABC def abc nbc wral abc def nbc abc