2014-12-04 65 views
1

我有一個像獲取IndexOutOfBounds異常,同時尋求subtring

var word = "banana" 

一個字符串,像var sent = "the monkey is holding a banana which is yellow"

sent1 = "banana!!" 

一句我想搜索在sent香蕉,然後寫在一個文件以下方式:

the monkey is holding a 
banana  
which is yellow 

我按照以下方式進行:

var before = sent.substring(0, sent.indexOf(word)) 
var after = sent.substring(sent.indexOf(word) + word.length) 
println(before) 
println(after) 

這工作正常,但是當我對sent1做同樣的事情時,它給了我IndexOutOfBoundsException。我認爲這是因爲發送香蕉之前一無所有。如何處理這個?

回答

3

您可以根據單詞進行分割,您將得到一個包含單詞前後所有內容的數組。

val search = sent.split(word) 
search: Array[String] = Array("the monkey is holding a ", " which is yellow") 

這個工程在「香蕉!!!」案例:

"banana!!".split(word) 
res5: Array[String] = Array("", !!) 

現在你可以寫三行到一個文件中自己喜歡的方式:

println(search(0)) 
println(word) 
println(search(1)) 
+0

它給我ArrayIndexOutOfBoundsException。 :O – 2014-12-04 20:13:03

+0

他可能是指'搜索(0)'和'搜索(1)' – Dimitri 2014-12-04 20:15:43

+0

肯定的,謝謝@Dimitri – Gangstead 2014-12-04 20:16:25

0

如果你有這個詞出現了多次? .split瞭解正則表達式,所以你可以改善的東西以前的解決方案是這樣的:那麼

string 
    .replaceAll("\\s+(?=banana)|(?<=banana)\\s+") 
    .foreach(println) 

\\s意味着一個空白字符 (?=<word>)手段「其次是<word>(?<=<word>)指「<word>之前」 ,這將把你的字符串分成幾塊,使用「香蕉」前後的任何空格,而不是單詞本身。實際的單詞結束於列表中,就像字符串的其他部分一樣,所以不需要明確地打印出來

這個正則表達式技巧被稱爲「正面環視」(?= look-前面,?< =是後視),以防萬一你想知道。