I have this Java code to trim a string
String title = titleEt.getText().toString().trim();
When I convert to kotlin, I expect this should be the kotlin code to trim the leading and trailing spaces.
val title = titleEt.text.toString().trim()
However, the IDE generates this code
val title = titleEt.text.toString().trim { it <= ' ' }
What is this { it <= ' ' } here? Is it any char less and than ' '?
Trim() Removes all leading and trailing white-space characters from the current string.
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.
trim function in kotlin allows a predicate so trim in java code (removes the white spaces) is the same as .trim { it <= ' ' }
You can use .trim()
in kotlin too
Java's String#trim()
removes all codepoints between '\u0000'
(NUL) and '\u0020'
(SPACE) from the start and end of the string.
Kotlin's CharSequence.trim()
removes only leading and trailing whitespace by default (characters matching Char.isWhitespace
, which is Character#isWhitespace(char)
). For the same behavior as Java, the IDE generated a predicate that matches the same characters that Java would have trimmed.
These characters include ASCII whitespace, but also include control characters.
'\u0000' ␀ ('\0') '\u0001' ␁ '\u0002' ␂ '\u0003' ␃ '\u0004' ␄ '\u0005' ␅ '\u0006' ␆ '\u0007' ␇ ('\a') '\u0008' ␈ ('\b') '\u0009' ␉ ('\t') '\u000A' ␊ ('\n') '\u000B' ␋ ('\v') '\u000C' ␌ ('\f') '\u000D' ␍ ('\r') '\u000E' ␎ '\u000F' ␏ '\u0010' ␐ '\u0011' ␑ '\u0012' ␒ '\u0013' ␓ '\u0014' ␔ '\u0015' ␕ '\u0016' ␖ '\u0017' ␗ '\u0018' ␘ '\u0019' ␙ '\u001A' ␚ '\u001B' ␛ '\u001C' ␜ '\u001D' ␝ '\u001E' ␞ '\u001F' ␟ '\u0020' ␠ (' ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With