David Pesetsky
David Pesetsky

Reputation: 294

Kotlin: strip first and last character

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

Answers (4)

k314159
k314159

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

AFAQUE JAYA
AFAQUE JAYA

Reputation: 31

Example : 1

    String loginToken = "[hello]";
    System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );

Output :

hello

Upvotes: 0

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

You can also do:

val str = "hello"
val myPiece = str.drop(1).dropLast(1)
println(myPiece)

Upvotes: 9

Leonardo Jaques
Leonardo Jaques

Reputation: 19

You can try this one:

val str = "myText"
var myPiece = str.substring(1, str.length -1)

print(myPiece)

Upvotes: 2

Related Questions