使用printf(format, args) 方法将格式化的字符串输出到控制台。 字符串连接: 使用+ 运算符连接字符串。 使用StringBuilder 或StringBuffer 的append() 方法高效地连接字符串。 字符串遍历: 使用for (char in string) 循环遍历字符串中的每个字符。 使用indices 属性获取字符串
fun append(vararg str: Char): String { val result = StringBuffer() for (char in str){ result.append(char) } return result.toString() } 传递可变数量的参数 append('k','o','t','l','i','n') if表达式 带返回值 if 表达式 在kotlin当中,由于if是一个表达式所以它会返回一个值,表达式...
//为 String 类声明一个扩展函数 lastChar() ,用于返回字符串的最后一个字符 //get方法是 String 类的内部方法,length 是 String 类的内部成员变量,在此处可以直接调用 fun String.lastChar() = get(length - 1) //为 Int 类声明一个扩展函数 doubleValue() ,用于返回其两倍值 //this 关键字代表了 Int...
但实际上我们使用时都是直接append就可以了,这是因为我们操作StringBuilder都在内存中,不会出现IO异常,因此AbstractStringBuilder在实现时去掉了抛出IO异常: @Override public AbstractStringBuilder append(CharSequence s) { if (s == null) { return appendNull(); } if (s instanceof String) { return this.app...
fun String.lastChar(): Char { return this.get(this.length - 1) } 1. 2. 3. 4. 5. 把要扩展的类或者接口的名称,放到即将添加的函数前面。这个类或者接口就被称为接收者类型;用来调用这个扩展函数的那个对象,叫作接收者对象。如下图所示:
stringBuffer.append(value) } stringBuffer.append(postfix) return stringBuffer.toString() } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 命名参数(又叫具名参数) ★ println(joinToString(list, separator = ",", prefix = "[ ", postfix = " ]")) ...
append(postfix) return result.toString() } fun main(args: Array<String>) { val list = listOf(1, 2, 3) println(joinToString(list, "; ", "(", ")")) } 基本类型 在Kotlin中,所有东西都是对象,所以我们可以调用成员函数和属性的任何变量对象。有些类型是内置的,他们的实现被优化过, 但是用户...
buffer.append(((byte.toInt() shr4) and0xFplus'a').toChar()) buffer.append(((byte.toInt()) and0xFplus'a').toChar()) }returnbuffer.toString() }privatefundecodeBytes(str: String) : ByteArray{varbytes = ByteArray(str.length() /2)for(iin0..(str.length() -1)) {varc = str....
(Char) -> Boolean): String { val sb = StringBuilder() for (index in 0 until length) { val element = get(index) // 调用作为参数传递给 predicate 的函数 if (predicate(element)) sb.append(element) } return sb.toString() } // 传递一个lambda作为 predicate 参数 ...
將指定數組的字符轉換為字符串的標準解決方案是使用 String 構造函數。 1 2 3 4 5 6 fun main() { val chars = charArrayOf('T', 'e', 'c', 'h') val str = String(chars) println(str) // Tech } 下載代碼 此外,可以將 String 構造函數調用為: 1 2 3 4 5 6 fun main() { val ch...