How to remove white space from the start of a String Kotlin?

Viewed 3362

I am trying to create a program which reads a .txt file and splits the file into separate lists.

I am using this to try and split my strings into 4 parts:

val parts = it.split("\\s".toRegex())

 val part1 = parts[0]
 val part2 = parts[1]
 val part3 = parts[2]
 val part4 = parts[3]

(The reason i am using "\s" is that the number of spaces between the words in inconsistent)

However, some lines in the file begin with a space or two which then results in the first word not being detected.

Is there a way for me to ignore or remove only the first white space of each line? As currently when i try to print part[0] it returns as blank

3 Answers

What you want is probably something like this:

val textLine = " part1 part2 part3  part4"

// wrong way
val parts = textLine.split("\\s".toRegex())
println(parts) // [, part1, part2, part3, , part4]

// correct way
val partsWithTrim = textLine.trim().split("\\s+".toRegex())
println(partsWithTrim) // [part1, part2, part3, part4]

Note the trim call to remove white spaces from the start and the end of the string and the + sign in the regex part to really deal with inconsistent number of spaces.

'val value = " hello kotlin"

value.trimstart() // output: "hello kotlin"

value.trim() // output: "hellokotlin" `

Simply trim the strings:

 val part1 = parts[0].trim()

or

 val part1 = parts[0].trimStart()
Related