2014-03-29 229 views
0

我試圖從其標點符號中分出一個單詞:將字符串拆分爲兩個

例如,如果單詞是「Hello?」。我想將「Hello」存儲在一個變量中,「?」在另一個變量。

我試過使用.split方法,但刪除了分隔符(標點符號),這意味着您不會保存標點符號。

String inWord = "hello?"; 
String word; 
String punctuation = null; 
if (inWord.contains(","+"?"+"."+"!"+";")) { 
    String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;"); 
    word = parts[0]; 
    punctuation = parts[1]; 
} else { 
    word = inWord; 
} 

System.out.println(word); 
System.out.println(punctuation); 

我被卡住了,我不能看到另一種做法。

在此先感謝

+0

你的if語句的狀態似乎對我沒有太大意義 – donfuxx

回答

3

你可以使用正向前查找分裂,所以你不實際使用的標點符號分裂,但之前的位置是正確的:

inWord.split("(?=[,?.!;])"); 

ideone demo

+0

順便說一下,你的'.contains'不檢查每個字符。您也許可以使用模式/匹配器方法,如[this](http://ideone.com/Z8ulS2)。 – Jerry

0

我認爲你可以使用下面的正則表達式。但沒有嘗試過。試一試。

input.split("[\\p{P}]") 
0

你可以在這裏使用子串。例如:

String inWord = "hello?"; 
    String word = inWord.substring (0, 5); 
    String punctuation = inWord.substring (5, inWord.length()); 

    System.out.println (word); 
    System.out.println (punctuation); 
1

除了其他建議,您還可以使用'字邊界'匹配器'\ b'。這可能並不總是與你正在尋找的東西匹配,它檢測到一個字和一個非字的邊界,如文件所示:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

在你的例子中,雖然數組中的第一個元素是空白串。

下面是一些工作代碼:

String inWord = "hello?"; 
String word; 
String punctuation = null; 
if (inWord.matches(".*[,?.!;].*")) { 
    String parts[] = inWord.split("\\b"); 
    word = parts[1]; 
    punctuation = parts[2]; 
    System.out.println(parts.length); 
} else { 
    word = inWord; 
} 

System.out.println(word); 
System.out.println(punctuation); 

你可以看到它運行在這裏:http://ideone.com/3GmgqD

我也修正了自己的.contains使用.matches來代替。

相關問題