将句子分解为单词和标点符号

时间:2014-01-04 20:47:06

标签: java string split

我需要将类Sentence解析为单词和标点符号(空格被视为标点符号),然后将所有内容添加到常规ArrayList<Sentence>中。

一句例句:

  

一个男人,一个计划,一条运河 - 巴拿马!   A =&gt;字
  whitespase =&gt;标点符号
  man =&gt;字
  ,+ space =&gt;标点符号
  a =&gt;字
  [...]

我试着一次一个字符地阅读整个句子并收集相同内容并从这个集合中创建新单词或新Punctuation

这是我的代码:

public class Sentence {

    private String sentence;
    private ArrayList<Word> words;
    private ArrayList<Punctuation> punctuations;

    /**
     * Constructs a sentence.
     * @param aText a string containing all characters of the sentence
     */
    public Sentence(String aText) {
        sentence = aText;

        int i = 0;
        while (Character.isLetter(sentence.charAt(i))) {  // I stuck here
            i++;
        }
    }

也许其他方法要好得多?有什么建议吗?

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

一个简单的解决方案是定义您认为是标点符号的内容并将其移到标点符号列表中。

您还可以通过字母将任何其他内容附加到字符串缓冲区。一旦你来到一个标点符号,你就可以存储前一个“单词”和标点符号。

使用StringBuffer附加你的字母以构建每个“单词”。

如果可以,最好使用for循环。然后,您可以检查是否有标点符号(添加前一个单词,添加标点符号然后清除StringBuffer)或将“letter”添加到StringBuffer。

答案 1 :(得分:0)

//before using sentence check if its null and not empty
char tempChar = sentence.charAt(0);
while (tempChar != '\n') {  
    if(tempChar == ' ' || tempChar == '+' || /* and so on */){
        //Add to punctuations
    }else if(Character.isLetter(tempChar)){

        //save the tempChar and continue (with incremental i )till you get a punctuation
        //Add to characters saved in words array
    }

    i++;
}

这不是一个正确的答案,但这是我在晚上2:30可以想到的内容lol

相关问题