我想了解indexOfScala中的第二個引數對字串意味著什么?
object Playground extends App {
val g: String = "Check out the big brains on Brad!"
println(g.indexOf("o",7));
}
上面的程式回傳:25這是我無法理解的原因?
它實際上是 last 的索引,o但它與 7 有什么關系?是否像第二個引數n回傳第 n 個字符出現的索引,如果n超過出現次數,則回傳最后一個當前元素的索引?
但如果是這樣的話,那就沒有意義了:
object Playground extends App {
val g: String = "Check out the big brains on Brad!"
(1 to 7).foreach(i => println(s"$i th Occurence = ${g.indexOf("o",i)} "))
}
輸出:
1 th Occurence = 6
2 th Occurence = 6
3 th Occurence = 6
4 th Occurence = 6
5 th Occurence = 6
6 th Occurence = 6
7 th Occurence = 25
來源:https : //www.scala-exercises.org/std_lib/infix_prefix_and_postfix_operators
uj5u.com熱心網友回復:
根據 Scala String 檔案,第二個引數是開始搜索的索引:
def indexOf(elem: Char, from: Int): Int
Finds index of first occurrence of some value in this string after or at some start index.
elem : the element value to search for.
from : the start index
returns : the index >= from of the first element of this string that is equal (as determined by ==) to elem, or -1, if none exists.
因此,在您的情況下,當您指定 7 時,這意味著您將查找位于索引 7 或之后的第一個字符“o”的索引。事實上,在你的字串中有兩個“o”,一個在索引 6,一個在索引 25。
uj5u.com熱心網友回復:
indexOf(int ch, int fromIndex)從指定的索引 ( fromIndex) 中查找字串中的字符。這意味著它開始查看第 7 個位置。
uj5u.com熱心網友回復:
展望未來,您需要學習閱讀官方檔案: indexOf:
def indexOf(elem: A, from: Int): Int
[use case] Finds index of first occurrence of some value in this general sequence after or at some start index.
Note: may not terminate for infinite-sized collections.
elem
the element value to search for.
from
the start index
returns
the index >= from of the first element of this general sequence that is equal (as determined by ==) to elem, or -1, if none exists.
我個人喜歡用 Intellij 跳轉到帶有CMD B.
不管你如何看待它:在你的開發流程中,你會經常訪問你正在使用的 lib 或 lang 的 manual\docs。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/372703.html
標籤:斯卡拉
