簡體   English   中英

將字符串分成兩部分

[英]Splitting a string into two

我正在嘗試從標點符號中拆分一個單詞:

例如,如果單詞是“ 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);

我被困住了,看不到另一種方法。

提前致謝

您可以使用正向前瞻進行拆分,因此您實際上並沒有使用標點符號進行拆分,而是在其前面的位置:

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

ideone演示

除了其他建議,您還可以使用“單詞邊界”匹配器“ \\ 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

我認為您可以使用以下正則表達式。 但是沒有嘗試過。 試試看。

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

您可以在此處使用子字符串。 像這樣:

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

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

暫無
暫無

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

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