将一个句子拆分成单词然后交换每个单词的第一个和最后一个字母

时间:2013-12-13 16:46:30

标签: java

我需要输入一个句子并让计算机将句子分成单词,然后交换每个单词的第一个和最后一个字母。我需要为此使用数组。到目前为止,我使用的代码可以输入一个单词并交换第一个和最后一个字母,但现在我需要修改它来输入一个句子。有关如何做到这一点的任何建议?我对阵列不是很熟悉。

public class FirstNLast {

    private String word;
    private String newWord;
    private StringBuilder strBuff;
    private int len;
    private char firstLetter;
    private char lastLetter;

    public FirstNLast() {
        word = "";
        newWord = "";
        strBuff = new StringBuilder();
        len = 0;
        firstLetter = ' ';
        lastLetter = ' ';
    }

    public void setWord(String word) {
        this.word = word;
    }

    public void compute() {
        len = word.length();
        firstLetter = word.charAt(0);
        lastLetter = word.charAt(len - 1);

        for (int i = 0; i < word.length(); i = i + 1) {
            if (word.charAt(i) == firstLetter) {
                strBuff.append(lastLetter);
            } else if (word.charAt(i) == lastLetter) {
                strBuff.append(firstLetter);
            } else {
                strBuff.append(word.charAt(i));
            }
            newWord = strBuff.toString();
        }
    }

    public String getNewWord() {
        return newWord;
    }
}

5 个答案:

答案 0 :(得分:2)

使用String.split(String)方法将句子拆分为空格。该方法将为您提供一个字符串数组(在您的情况下单词)。然后遍历数组并执行您需要执行的操作。

答案 1 :(得分:1)

这样的事情可以解决问题:

public String mutateSentence(String input) {
  String[] words = input.split(" ");
  String output = "";    
  for (int i=0;i<words.length;i++) {
    String modifiedWord = yourMethodOfFlippingLetters(words[i]);
    output += modifiedWord;
  }
  output.trim(); // removes the trailing space added
  return output;
}

答案 2 :(得分:1)

使用完整句子的课程:

FisrtNlast f = new FirstNLast()
String words[] = sentence.split(' ');
String words[] = sentence.split(' ');

String out = null;
for( word in words){
  f.setWord(word);
  f.compute();
  out +=' ' + f.getNewWord();
}

sysout(out);

答案 3 :(得分:1)

首先,您需要将句子拆分为单独的单词组件。 Split方法基本上将句子分成每个空格。

String sentence = "The quick brown fox";
String[] words = sentence.Split(" ");

所以在这里,单词会相等:

{ "The", "quick", "brown", "fox" }

现在每个单词都被分开并放入一个数组中,您可以遍历数组并交换第一个和最后一个字母。

for(int i = 0; i < words.length; i++)
{
    char[] wordCharArray = word[i].toCharArray();
    char firstLetter = wordCharArray[0]; // Holds the first so we can replace it.
    wordCharArray[0] = wordCharArray[wordCharArray.length - 1]; // Sets the first letter as the last.
    wordCharArray[wordCharArray.length - 1] = firstLetter; // Sets the last letter as the original first.
    words[i] = new String(wordCharArray); // Just converts the char array back into a String.
}

sentence = new String(words);

答案 4 :(得分:0)

像这样使用split()

String word,output = "";
String something = "This is a sentence with some words and spaces";
String[] parts = something.split(" ");
for(int i = 0; i < parts.length; i++){
    word = flipLetters(parts[i]); /* swap the letters in the word*/
    output += word + " ";
}