2

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?

MarianD
  • 13,096
  • 12
  • 42
  • 54
David Pesetsky
  • 254
  • 5
  • 13
  • 2
    what compile error? There is no compile error, unless you dont have str defined. https://pl.kotl.in/TeuDY5asw, and to strip the first char you need to start with 1, not 0 – Dmitri Apr 29 '20 at 02:39

4 Answers4

9

You can also do:

val str = "hello"
val myPiece = str.drop(1).dropLast(1)
println(myPiece)
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • This creates an intermediate string after the call to `drop(1)`. You don't want to be doing this inside a performance-critical loop. `substring(1, str.length - 1)` creates only a single string. – k314159 Aug 10 '23 at 16:31
2

You can try this one:

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

print(myPiece)

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
0

Example : 1

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

Output :

hello
AFAQUE JAYA
  • 31
  • 1
  • 13
0

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?".

k314159
  • 5,051
  • 10
  • 32