2015-12-21 221 views
-1

我必須在字符串中找到*的出現位置,並且根據字符串中*的位置必須執行某些操作。正則表達式來查找字符的位置

if(* found in the beginning of the String) { 
do this 
} 
if(* found in the middle of the String) { 
do this 
} 
if(* found at the end of the String) { 
do this 
} 

我使用matcher.find()選項,但它沒有給出所需的結果。

+9

你爲什麼不用'indexOf()'? – TheLostMind

+2

[Java:獲取字符串匹配位置的方法?]的可能重複(http://stackoverflow.com/questions/2615749/java-method-to-get-position-of-a-match-in-字符串) – Fundhor

+0

「它沒有給出預期的結果」它給你什麼結果?對於什麼輸入?期望的結果是什麼? –

回答

7

使用String.indexOf

int pos = str.indexOf('*'); 
if (pos == 0) { 
    // Found at beginning. 
} else if (pos == str.length() - 1) { 
    // Found at end. 
} else if (pos > 0) { 
    // Found in middle. 
} 

另一種方法是使用startsWith/endsWith/contains

if (str.startsWith('*')) { 
    // Found at beginning. 
} else if (str.endsWith('*')) { 
    // Found at end. 
} else if (str.contains('*')) { 
    // Found in middle. 
} 

這可能是輕微更有效,因爲它避免了檢查整個字符串的情況下,它以*結尾。然而,代碼的可讀性應該是在這兩者之間進行選擇時的主要關注點,因爲在許多情況下性能差異可以忽略不計。

而且,當然,如果您使用後一種方法,則無法獲得*的實際位置。這取決於你是否真的試圖去做這件事情。

+0

startsWith( 「」)endsWith(「」)也可能有用。 – Fundhor

+1

@Fundhor好的,但是如果你要提到這些,你也需要在那個列表中包含'contains'。隨意添加你自己的答案,這是一個有效的方法。 –

+0

nope,你的回答很好,沒有意義加我自己的。只是它可以用於不同的情況(用於信息)。 – Fundhor

相關問題