Converting a sentence string to a string array of words in Java

后端 未结 16 2442
余生分开走
余生分开走 2020-12-01 00:04

I need my Java program to take a string like:

\"This is a sample sentence.\"

and turn it into a string array like:

{\"this\         


        
16条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 00:35

    You can use BreakIterator.getWordInstance to find all words in a string.

    public static List getWords(String text) {
        List words = new ArrayList();
        BreakIterator breakIterator = BreakIterator.getWordInstance();
        breakIterator.setText(text);
        int lastIndex = breakIterator.first();
        while (BreakIterator.DONE != lastIndex) {
            int firstIndex = lastIndex;
            lastIndex = breakIterator.next();
            if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) {
                words.add(text.substring(firstIndex, lastIndex));
            }
        }
    
        return words;
    }
    

    Test:

    public static void main(String[] args) {
        System.out.println(getWords("A PT CR M0RT BOUSG SABN NTE TR/GB/(G) = RAND(MIN(XXX, YY + ABC))"));
    }
    

    Ouput:

    [A, PT, CR, M0RT, BOUSG, SABN, NTE, TR, GB, G, RAND, MIN, XXX, YY, ABC]
    

提交回复
热议问题