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

后端 未结 16 2394
余生分开走
余生分开走 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:46

    Try using the following:

    String str = "This is a simple sentence";
    String[] strgs = str.split(" ");
    

    That will create a substring at each index of the array of strings using the space as a split point.

    0 讨论(0)
  • 2020-12-01 00:46

    Another way to do that is StringTokenizer. ex:-

     public static void main(String[] args) {
    
        String str = "This is a sample string";
        StringTokenizer st = new StringTokenizer(str," ");
        String starr[]=new String[st.countTokens()];
        while (st.hasMoreElements()) {
            starr[i++]=st.nextElement();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 00:46

    You can use simple following code

    String str= "This is a sample sentence.";
    String[] words = str.split("[[ ]*|[//.]]");
    for(int i=0;i<words.length;i++)
    System.out.print(words[i]+" ");
    
    0 讨论(0)
  • 2020-12-01 00:49

    You can also use BreakIterator.getWordInstance.

    0 讨论(0)
提交回复
热议问题