Reputation: 294
In Kotlin, I need to strip the first and last characters from a string. This seems to be getting compile errors:
val MyPiece = str.substring(0, str.length - 1)
What's wrong here?
Upvotes: 2
Views: 7052
Reputation: 11120
Care needs to be taken in case the first or last character is an emoji:
fun main() {
val str = "šxyzš"
println(
str.substring(
if (str.first().isSurrogate()) 2 else 1,
str.length - if (str.last().isSurrogate()) 2 else 1
)
)
}
Output:
xyz
The other answers don't work with surrogate pairs, and return "?xyz?".
Upvotes: 0
Reputation: 31
Example : 1
String loginToken = "[hello]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );
Output :
hello
Upvotes: 0
Reputation: 12953
You can also do:
val str = "hello"
val myPiece = str.drop(1).dropLast(1)
println(myPiece)
Upvotes: 9
Reputation: 19
You can try this one:
val str = "myText"
var myPiece = str.substring(1, str.length -1)
print(myPiece)
Upvotes: 2