簡體   English   中英

Java:按特殊字符和空格拆分字符串

[英]Java: Split a string by special characters and spaces

我是java的新手,我必須為一個短語創建一個豬拉丁語翻譯器。 這是我現在的代碼,以便我可以分割用戶輸入的短語。 抱歉格式不正確。

String english = "Queen of all reptiles";
String[] words = english.split ("\\s+"); 
for (int i = 0 ; i < words.length ; i++) {
    System.out.println (words [i]);
}

此代碼的輸出是:

Queen   
of    
all   
reptiles   

但是,我想用空格和特殊字符拆分String english,以便if

String english  = "Queen. of reptiles."

它會輸出:

Queen   
.   
of   
reptiles  
.

我試圖這樣做: String[] words = english.split ("[^a-zA-Z0-9]", ""); 但它不起作用。

您可以將以下內容用於字符串大小寫。

String s  = "Queen. of reptiles.";
String[] parts = s.split("(?=\\.)|\\s+");
System.out.println(Arrays.toString(parts));

產量

[Queen, ., of, reptiles, .]

似乎有一個討論使用split和look-behinds來實現這一點:

如何拆分字符串,還要保留分隔符?

正如Luiggi Mendoza在他的評論中所描述的那樣,這將如您所述:

String english = "Queen. of reptiles.";
Pattern p = Pattern.compile("\\w+|\\.");
Matcher m = p.matcher(english);

do {
   if (m.find()) {
      System.out.println(m.group());
   }
} while (!m.hitEnd());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM