切换字符串中多个单词的第一个和最后一个字母

qnzebej0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(376)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

上个月关门了。
改进这个问题
我不知道如何处理这个问题。我见过有人使用数组,但在尝试之后,它只对整个字符串有效,而不是每个单词单独使用。谢谢你的帮助!

ltskdhd1

ltskdhd11#

可以使用split方法将字符串拆分为多个单词,保存在字符串数组中。然后,使用charat方法获得第一个和最后一个字母,然后按照正确的顺序将它们连接起来,得到修改后的单词。

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 
        }

您似乎是java的初学者,因此我强烈建议您阅读有关string类及其方法的java文档,因为java有一些非常全面且相对容易理解的文档。

相关问题