以下是一些常用的 String 方法示例:
1.获取字符串长度:
val str = "Hello, Kotlin"
val length = str.length
2.字符串比较:
val str1 = "apple"
val str2 = "banana"
val compareResult = str1.compareTo(str2)
val compareResult = str1.equals(str2)
3.子字符串:
val str = "Hello, Kotlin"
val subStr = str.substring(7, 12) // 提取子字符串 "Kotlin"
val subStr = str.subSequence(7, 12) // 提取子字符串 "Kotlin"
4.大小写转换
val str = "Kotlin Programming"
val lowerCase = str.toLowerCase()
val upperCase = str.toUpperCase()
5.判断前缀和后缀:
val str = "Kotlin Programming"
val startsWith = str.startsWith("Kotlin")
val endsWith = str.endsWith("Programming")
6.替换字符串
val str = "Hello, Java"
val replacedStr = str.replace("Java", "Kotlin")
7.拆分字符串:
val str = "apple,banana,orange"
val fruits = str.split(",")
8.去除空格:
val str = " Kotlin Programming "
val trimmedStr = str.trim() // 去除前导和尾部空格
9.字符串连接:
val str1 = "Hello"
val str2 = "Kotlin"
val combinedStr = str1 + " " + str2
10.查找子字符串的位置:
val str = "Hello, Kotlin"
val index = str.indexOf("Kotlin") // 返回子字符串的起始位置
11.是否包含子字符串
val str = "Hello, Kotlin"
val contains = str.contains("Kotlin")
12.正则表达式匹配
val str = "Email: contact@example.com"
val isEmail = str.matches(Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}"))
13.格式化字符串
val name = "Alice"
val age = 30
val formattedStr = "Name: $name, Age: $age"
14.字符串分割成字符列表:
val str = "Kotlin"
val charList = str.toList()
15.字符串反转:
val str = "Kotlin"
val reversedStr = str.reversed()
16.字符串去重
val str = "aaabbbccc"
val uniqueStr = str.toSet().joinToString("")
17.检查字符串是否为空
val str = ""
val isEmpty = str.isEmpty()
val isBlank = str.isBlank() // 空格也算空
18.格式化输出
val name = "John"
val age = 25
println("Name: %s, Age: %d".format(name, age))