由於大家都把一個建議,將工作;我正在調整一個更有效和安全的建議。
String word = keyboard.nextLine();
這不保證一個字。它返回一行,這意味着換行符「\ n」之前的任何內容。
要得到的話,你應該使用:
String[] words = keyboard.nextLine().split(new char[] { ' ', '\t', '\r' });
這將拆分上的字符行:空格,製表符和回車(注:不換行)。
接下來我們通過每一個字需要循環使用for-each循環:
for(String word : words)
{
int wordLength = word.length(); // Get length, because we're gonna use it multiple times
if(wordLength > 0) // Ignore empty words
{
// Only get the first character and convert it to uppercase (better than using substring)
// Also note that we don't have to check if there's a character at 0, because we already did with wordLength > 0
char firstCharacter = Character.toUpperCase(word.charAt(0));
StringBuilder builder = new StringBuilder(firstCharacter); // We use StringBuilder class because it is efficient in concatenating objects to a string
if(wordLength == 2) // We only got 2 characters, so no inbetween
{
char lastCharacter = Character.toUpperCase(word.charAt(1)); // We know this character is at index 1
builder.append(lastCharacter); // Append last character
}
else // More than 2
{
String inbetweenCharacters = word.substring(1, wordLength - 2); // Get the words in between using substring
char lastCharacter = Character.toUpperCase(word.charAt(wordLength - 1)); // Get the last character
builder.append(inbetweenCharacters); // Append inbetween characters
builder.append(lastCharacter); // Append last character
}
System.out.println(builder.toString()); // Print complete converted word
}
}
我這樣做對我的頭頂,我希望這不會有任何錯別字
字符串lettersBetween = word.substring(1,stringLength - 1) ? – RuntimeException
你似乎知道如何接受一部分字符串。您只需在第一個字母和最後一個字母之前參加並將其添加到第一個和最後一個字符的高版本。 – Pshemo