【问题标题】:Switch the first and last letter of multiple words in a string [closed]切换字符串中多个单词的第一个和最后一个字母[关闭]
【发布时间】:2021-03-07 14:55:27
【问题描述】:

我不确定如何解决这个问题。我见过人们使用数组,但在尝试之后,它只适用于整个字符串,而不是单独的每个单词。 感谢您的帮助!

【问题讨论】:

  • 您需要单独处理每个单词。你知道如何从字符串中获取单词列表吗?
  • 遗憾的是:/ - 我可以搜索一下
  • 先将字符串拆分成单词,然后再进行操作使其简单
  • 在这里向我们展示你做了什么?

标签: java string char


【解决方案1】:

您可以使用 split 方法将字符串拆分为多个单词,保存在 String 数组中。然后,使用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 documentation,因为 Java 有一些非常全面且相对容易理解的文档。

【讨论】:

  • 非常感谢!以后我会查看链接寻求帮助!
  • 没问题,乐于助人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2020-02-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
相关资源
最近更新 更多