2013-12-13 144 views
2

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

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; 
    } 
} 
+0

查看'split()'方法。 – Floris

回答

2

使用String.split(String)方法将句子拆分为空格。该方法将给你一个字符串数组(在你的情况下)。然后遍历数组,并做你需要做的事情。

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; 
} 
0

使用分裂()这样的

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 + " "; 
} 
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); 
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); 
相关问题