kotlin 中 trim{it <= ' '} 和 trim 之间的区别?

Difference between trim{it <= ' '} and trim in kotlin?

trim in kotlin remove space int leading and trailing, but when android studio 将 java 代码转换为 kotlin,将 java 中的 trim() 转换为 kotlin 中的 trim{it <= ' '} 将其更改为 trim 时,没有任何区别。 trim 和 trim{it <= ' '} 之间有什么区别??

根据文档:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim.html

fun String.trim(): String Returns a string having leading and trailing whitespace removed.

it <= ' ' 将删除所有 ascii code 小于或等于 space 的 'non printable' 字符(ascii 十进制 = 32)作为回车符 return,换行...

我刚刚测试了许多这样的字符:

val kotlin = "\t\t"
println(kotlin)
   
val kotlin2 = "\t\t".trim()
println(kotlin2)
   
val kotlin3 = "\t\t".trim{it <= ' '}
println(kotlin3)

这输出:

      


他们都清理了这个字符。正如@AlexeyRomanov 所说,kotlin 将使用 isWhitespace 方法理解为 return true 的字符理解为 whitespace 字符。所以 it <= ' ' 是让它只 trim 与 java 相同的字符,而不是根据 Unicode 标准的其他白色 space 字符。

如果我们测试 \u00A0 字符:

val kotlin4 = "\u00A0\u00A0".trim()
println(kotlin4)
   
val kotlin5 = "\u00A0\u00A0".trim{it <= ' '}
println(kotlin5)

我们可以看到输出的差异:


  

您可以在 kotlin playground.

中进行测试

Java的trim documentation

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a String object representing an empty string is returned.

Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m + 1).

所以条件正好是{ it <= ' ' }(其中it是字符串中的一个字符)。

Kotlin 代替 uses

public fun CharSequence.trim(): CharSequence = trim(Char::isWhitespace)

这是真的,例如对于不间断的 space \u00A0、Ogham space 标记 \u1680 等,对于 ' ' 以下的某些字符(例如 \u0001)为 false。