scala獲取字符串首字符和尾字符

一、獲取第一個元素

1.take()

scala> "hello".take(1)
res12: String = h

2.索引法

因爲字符串的本質是字符數組

scala> "hello"(0)
res13: Char = h

3.字符串截取

scala> "hello".substring(0,1)
res15: String = h

 

二、獲取最後一個元素

1.先反轉再獲取第一個

scala> "Hello".reverse.take(1)
res11: String = o

2.takeRight()

scala> "hello".takeRight(1)
res14: String = o

3.字符串截取

scala> "hello".substring("hello".length-1)
res16: String = o

 

發佈了40 篇原創文章 · 獲贊 23 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章