在 Scala 中,charAt 函数用于返回字符串指定位置的字符,第一个字符的索引为 0。
char charAt(int index)
参数 | 描述 |
---|---|
index | 要返回的索引。 |
返回 index 索引处的字符,index 从 0 开始。
使用 charAt 函数,实现返回指定位置处字符
object HaiCoder {
val greeting: String = "Hello, World!"
def main(args: Array[String]) : Unit = {
println("嗨客网(www.haicoder.net)!\n")
var ch1 = greeting.charAt(0)
var ch2 = greeting.charAt(1)
var ch3 = greeting.charAt(2)
printf("ch1 = %c, ch2 = %c, ch3 = %c\n", ch1, ch2, ch3)
}
}
程序运行后,控制台输出如下:
我们使用了 charAt 函数分别返回了字符串变量 greeting 的第一个字符、第二个字符和第三个字符。
在 Scala 中,charAt 函数用于返回字符串指定位置的字符,第一个字符的索引为 0。