String a = "This is a string with multiple words";
String[] arr = a.split(" "); //splits string into an array of strings, by separating with spaces
for (int i = 0; i < arr.length; i++) //looping through each word
{
if (arr[i].length() == 1) //don't change word if it only has 1 letter
{
System.out.print(arr[i] + " ");
continue;
}
//using charAt to obtain first and last letter of each word
char firstLetter = arr[i].charAt(0);
char lastLetter = arr[i].charAt(arr[i].length()-1);
String middle = arr[i].substring(1, arr[i].length()-1); //all letters of word except first and last
arr[i] = lastLetter + middle + firstLetter; //concatenating together to create new word
System.out.print(arr[i] + " "); //printing each word after switching letters
}
1条答案
按热度按时间ltskdhd11#
可以使用split方法将字符串拆分为多个单词,保存在字符串数组中。然后,使用charat方法获得第一个和最后一个字母,然后按照正确的顺序将它们连接起来,得到修改后的单词。
您似乎是java的初学者,因此我强烈建议您阅读有关string类及其方法的java文档,因为java有一些非常全面且相对容易理解的文档。