【问题标题】:Converting a sentence string to a string array of words in Java在Java中将句子字符串转换为单词的字符串数组
【发布时间】:2011-06-08 04:09:03
【问题描述】:

我需要我的 Java 程序获取如下字符串:

"This is a sample sentence."

然后把它变成一个字符串数组,比如:

{"this","is","a","sample","sentence"}

没有句点或标点符号(最好)。顺便说一句,字符串输入总是一个句子。

有没有一种我没有看到的简单方法来做到这一点?还是我们真的需要大量搜索空格并从空格之间的区域(即单词)创建新字符串?

【问题讨论】:

标签: java string spaces words


【解决方案1】:

String.split() 会做大部分你想做的事。然后,您可能需要遍历单词以提取任何标点符号。

例如:

String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
    // You may want to check for a non-word character before blindly
    // performing a replacement
    // It may also be necessary to adjust the character class
    words[i] = words[i].replaceAll("[^\\w]", "");
}

【讨论】:

  • 你能补充一下你使用的正则表达式的解释吗?
  • @Marek 1. \\s 表示空格,\\s+ 表示多个空格 2. .replaceAll("[^\\w]", "");和 .replaceAll("\\W", "");它们都将替换除 [a-zA-Z0-9_] 之外的字符。如果您也想替换下划线,请使用:[\\W_]
  • 它工作正常,虽然我有赞成票,但是如果存在任何特殊字符,这个正则表达式会删除任何!如果有任何正常的正则表达式不会删除任何字符,请更新
【解决方案2】:

现在,这可以通过split 来完成,因为它需要正则表达式:

String s = "This is a sample sentence with []s.";
String[] words = s.split("\\W+");

这将给出:{"this","is","a","sample","sentence", "s"}

\\W+ 将匹配所有出现一次或多次的非字母字符。所以没有必要更换。您也可以检查其他模式。

【讨论】:

  • 您可能希望以(?U) 开始正则表达式以启用Unicode 字符类,否则它将仅适用于英文字母。
【解决方案3】:

您可以使用@987654321@ 查找字符串中的所有单词。

public static List<String> getWords(String text) {
    List<String> words = new ArrayList<String>();
    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;
}

测试:

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))"));
}

输出:

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

【讨论】:

  • 不拆分 x.y ,即“funny.Does it split”,返回funny.Does as 1 word
  • 它可能不应该。在英语中——遗憾的是,代码没有指定语言环境——单词不被句点分隔。
【解决方案4】:

您也可以使用@987654321@

【讨论】:

  • 哇。该文档看起来非常好。一种在字符串中查找单词的简单方法。
【解决方案5】:

你可以使用这个 regular 表达式来分割你的字符串

String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/>
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+");

【讨论】:

  • 适合法语。您可以添加一些内容,例如:“[[ ]*|[,]*|[;]*|[:]*|[']*|[']*|[\\.]*|[:]* |[/]*|[!]*|[?]*|[+]*]+"
【解决方案6】:

尝试使用以下方法:

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

这将使用空间作为分割点在字符串数组的每个索引处创建一个子字符串。

【讨论】:

    【解决方案7】:

    我能想到的最简单最好的答案是使用java字符串上定义的以下方法-

    String[] split(String regex)
    

    只需执行“This is a sample sentence”.split(" ")。因为它需要一个正则表达式,所以您也可以进行更复杂的拆分,包括删除不需要的标点符号和其他此类字符。

    【讨论】:

    • 如果句子没有标点符号,这是最简单的解决方案。
    【解决方案8】:

    使用string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ') 将您的代码拆分为一个没有句点、逗号、问号或感叹号的数组。您可以根据需要添加/删除任意数量的替换调用。

    【讨论】:

    • 与其调用 replace 4 次,不如使用捕获 4 个项目中任何一个的正则表达式调用一次。
    【解决方案9】:

    试试这个:

    String[] stringArray = Pattern.compile("ian").split(
    "This is a sample sentence"
    .replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars
    );
    
    for (int j=0; i<stringArray .length; j++) {
      System.out.println(i + " \"" + stringArray [j] + "\"");
    }
    

    【讨论】:

      【解决方案10】:

      我已经在某个地方发布了这个答案,我会在这里再次发布。此版本不使用任何主要的内置方法。 你得到了 char 数组,将其转换为字符串。希望对你有帮助!

      import java.util.Scanner;
      
      public class SentenceToWord 
      {
          public static int getNumberOfWords(String sentence)
          {
              int counter=0;
              for(int i=0;i<sentence.length();i++)
              {
                  if(sentence.charAt(i)==' ')
                  counter++;
              }
              return counter+1;
          }
      
          public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring() 
          {
              int counter=0;
              char charArrayToReturn[]=new char[end-start];
              for(int i=start;i<end;i++)
              {
                  charArrayToReturn[counter++]=sentence.charAt(i);
              }
              return charArrayToReturn;
          }
      
          public static char[][] getWordsFromString(String sentence)
          {
              int wordsCounter=0;
              int spaceIndex=0;
              int length=sentence.length();
              char wordsArray[][]=new char[getNumberOfWords(sentence)][]; 
              for(int i=0;i<length;i++)
              {
                  if(sentence.charAt(i)==' ' || i+1==length)
                  {
                  wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
                  spaceIndex=i+1; //increment space index
                  }
              }
              return  wordsArray; //return the 2 dimensional char array
          }
      
      
          public static void main(String[] args) 
          {
          System.out.println("Please enter the String");
          Scanner input=new Scanner(System.in);
          String userInput=input.nextLine().trim();
          int numOfWords=getNumberOfWords(userInput);
          char words[][]=new char[numOfWords+1][];
          words=getWordsFromString(userInput);
          System.out.println("Total number of words found in the String is "+(numOfWords));
          for(int i=0;i<numOfWords;i++)
          {
              System.out.println(" ");
              for(int j=0;j<words[i].length;j++)
              {
              System.out.print(words[i][j]);//print out each char one by one
              }
          }
          }
      
      }
      

      【讨论】:

        【解决方案11】:

        string.replaceAll() 不能正确使用与预定义不同的语言环境。至少在jdk7u10中。

        此示例使用 windows cyrillic charset CP1251 从文本文件创建一个单词字典

            public static void main (String[] args) {
            String fileName = "Tolstoy_VoinaMir.txt";
            try {
                List<String> lines = Files.readAllLines(Paths.get(fileName),
                                                        Charset.forName("CP1251"));
                Set<String> words = new TreeSet<>();
                for (String s: lines ) {
                    for (String w : s.split("\\s+")) {
                        w = w.replaceAll("\\p{Punct}","");
                        words.add(w);
                    }
                }
                for (String w: words) {
                    System.out.println(w);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        

        【讨论】:

          【解决方案12】:

          下面是一个代码 sn-p,它将句子拆分为单词并给出它的计数。

           import java.util.HashMap;
           import java.util.Iterator;
           import java.util.Map;
          
           public class StringToword {
          public static void main(String[] args) {
              String s="a a a A A";
              String[] splitedString=s.split(" ");
              Map m=new HashMap();
              int count=1;
              for(String s1 :splitedString){
                   count=m.containsKey(s1)?count+1:1;
                    m.put(s1, count);
                  }
              Iterator<StringToword> itr=m.entrySet().iterator();
              while(itr.hasNext()){
                  System.out.println(itr.next());         
              }
              }
          
          }
          

          【讨论】:

            【解决方案13】:

            另一种方法是 StringTokenizer。 例如:-

             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();
                }
            }
            

            【讨论】:

              【解决方案14】:

              您可以使用以下简单的代码

              String str= "This is a sample sentence.";
              String[] words = str.split("[[ ]*|[//.]]");
              for(int i=0;i<words.length;i++)
              System.out.print(words[i]+" ");
              

              【讨论】:

                【解决方案15】:

                这里的大多数答案都按照问题将 String 转换为 String Array。但是一般我们使用 List ,所以更有用的是 -

                String dummy = "This is a sample sentence.";
                List<String> wordList= Arrays.asList(dummy.split(" "));
                

                【讨论】:

                  【解决方案16】:

                  这里有一个简单的 C++ 代码解决方案,没有花哨的功能,使用 DMA 分配一个动态字符串数组,然后将数据放入数组中,直到找到一个开放空间。 请使用 cmets 参考下面的代码。 希望对你有帮助。

                  #include<bits/stdc++.h>
                  using namespace std;
                  
                  int main()
                  {
                  
                  string data="hello there how are you"; // a_size=5, char count =23
                  //getline(cin,data); 
                  int count=0; // initialize a count to count total number of spaces in string.
                  int len=data.length();
                  for (int i = 0; i < (int)data.length(); ++i)
                  {
                      if(data[i]==' ')
                      {
                          ++count;
                      }
                  }
                  //declare a string array +1 greater than the size 
                  // num of space in string.
                  string* str = new string[count+1];
                  
                  int i, start=0;
                  for (int index=0; index<count+1; ++index) // index array to increment index of string array and feed data.
                  {   string temp="";
                      for ( i = start; i <len; ++i)
                      {   
                          if(data[i]!=' ') //increment temp stored word till you find a space.
                          {
                              temp=temp+data[i];
                          }else{
                              start=i+1; // increment i counter to next to the space
                              break;
                          }
                      }str[index]=temp;
                  }
                  
                  
                  //print data 
                  for (int i = 0; i < count+1; ++i)
                  {
                      cout<<str[i]<<" ";
                  }
                  
                      return 0;
                  }
                  

                  【讨论】:

                    【解决方案17】:

                    这应该会有所帮助,

                     String s = "This is a sample sentence";
                     String[] words = s.split(" ");
                    

                    这将创建一个数组,其中元素为以“”分隔的字符串。

                    【讨论】:

                      【解决方案18】:

                      试试这个....

                      import java.util.Scanner;
                      
                      public class test {
                          public static void main(String[] args) {
                      
                              Scanner t = new Scanner(System.in);
                              String x = t.nextLine();
                      
                              System.out.println(x);
                      
                              String[] starr = x.split(" ");
                      
                              System.out.println("reg no: "+ starr[0]);
                              System.out.println("name: "+ starr[1]);
                              System.out.println("district: "+ starr[2]);
                      
                          }
                      }
                      

                      【讨论】:

                        猜你喜欢
                        • 2021-02-11
                        • 2012-01-18
                        • 2016-05-22
                        • 2013-11-27
                        • 2023-03-19
                        • 1970-01-01
                        • 2016-02-04
                        相关资源
                        最近更新 更多