我试图只交换第一个单词的第一个字母。
这是我到目前为止所做的。
import java.util.Scanner;
public class Ass2ID7239 {
public static void main(String[] args) {
System.out.println("Please enter a line of text without any punctuation:");
System.out.print("> " );
Scanner sc = new Scanner( System.in );
String input = sc.nextLine();
System.out.print("I have changed your text: ");
input.trim();
int firstSpace = input.indexOf(" ");
int lastSpace = input.lastIndexOf(" ");
String firstWord = input.substring(0, firstSpace + 1);
String middlePhrase = input.substring(firstSpace + 1, lastSpace);
String lastWord = input.substring(lastSpace, input.length());
lastWord = lastWord.toUpperCase();
System.out.println(lastWord + " " + middlePhrase + " " + firstWord);
}
}
答案 0 :(得分:2)
尝试
input.substring(0,1).toUpperCase() + input.substring(1).toLowerCase();
答案 1 :(得分:0)
一些更正; lastWord以空格开始。
input = input.trim();
int firstSpace = input.indexOf(" ");
int lastSpace = input.lastIndexOf(" ");
String firstWord = input.substring(0, firstSpace);
String middlePhrase = input.substring(firstSpace + 1, lastSpace);
String lastWord = input.substring(lastSpace + 1);
if (!lastWord.isEmpty() {
lastWord = lastWord.substring(0, 1).toUpperCase() + lastWord.substring(1);
}
System.out.println(lastWord + " " + middlePhrase + " " + firstWord);