简体   繁体   中英

Split String in two Kotlin

I have one string that if have more than 35 characters have to been split in another string. Something like that var string1 = "1...38" into var result1= "1...35 " and var result2 = "36...38" . I thinking in using a split but i don't know if is the best option.

chunked(size: Int) will give you back your string split into a list:

"Hello There! This is a really long string that I want split".chunked(10)

Result

["Hello Ther", "e! This is", "a really" , "long strin", "g that I w", "ant split"]

You should rather use

drop and droplast (returns a String)

val chars = "abcdefghijklmnopqrstuvwxyzabcdefghijkl"
val result1 = chars.dropLast(3) // returns abcdefghijklmnopqrstuvwxyzabcdefghi
val result2 = chars.drop(35) // returns jkl

or chunked (returns a list of strings)

chars.chunked(35)) // returns [abcdefghijklmnopqrstuvwxyzabcdefghi, jkl]

that depends on your context

This extension will give you a pair of the limited string associated to the rest:

fun String.limit(max: Int): Pair<String, String> =
    if (length > max) {
        take(max) to takeLast(length - max)
    } else this to ""

Some examples:

val string1 = "onqweinalsdmuizqbwnöfasdkdasqwrwfeqewwqeweqewf" //more than 35
val string2 = "onqweinalsdmuizqbwnöfasdkdasqwrwfeq" //exactly 35
val string3= "asdqwe" //less than 35

println(string1.limit(35))    // -> (onqweinalsdmuizqbwnöfasdkdasqwrwfeq, ewwqeweqewf)
println(string2.limit(35))    // -> (onqweinalsdmuizqbwnöfasdkdasqwrwfeq, )
println(string3.limit(35))    // -> (asdqwe, )

Chunked method is what you need. Check this doc ->

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html

chunked is definitely ok if chunking into more then 2 pieces is ok for you too. But if you rather meant splitting it up into at most 2 pieces with the first being of a certain length and the second part only containing the remainder, you may want to use something like the following instead (similar to s1m0nw1s answer , but) using take and substring :

fun String.splitAtIndex(index : Int) = take(index) to substring(index)

Or if you want to play it safe, you can also add some convenience checks:

fun String.splitAtIndex(index: Int) = when {
  index < 0 -> 0
  index > length -> length
  else -> index
}.let {
  take(it) to substring(it)
}

or if you like exceptions more:

fun String.splitAtIndex(index: Int) = require(index in 0..length).let {
  take(index) to substring(index)
}

All of those functions return you a Pair<String, String> , which you can handle as follows:

"someString".splitAtIndex(5).also { (atMost5Chars, remainder) ->
   println("$atMost5Chars | remainder: $remainder")
}
"someOther".splitAtIndex(4).also { 
   (first) -> println(first) // discard the remainder... but then again you could have used also just take(4)
}

As you wrote that you thought of using split and if you have an appropriate delimiter at hand you may also want to use the following instead:

yourInputString.split(yourDelimiter, limit = 2)

This will split yourInputString into two pieces where the first piece is all the string up to the first occurrence of yourDelimiter . Example:

val yourInputString = "this is a string with a delimiter | and some more information that is not necessary | with some more delimiters | | |"
yourInputString.split('|', limit = 2).also {
  (uptoFirstDelimiter, remainder) -> println("$uptoFirstDelimiter --- remainder: $remainder")
}

which will print:

this is a string with a delimiter  --- remainder:  and some more information that is not necessary | with some more delimiters | | |

I came across similar scenario in card payment where expiry month/year is needed to split for api and pass separate params to.network repository and this is how it done. The Solution: var expiryMonth:String="12/2034" expiryMonth.split("/").also { (uptoFirstDelimiter, remainder) -> println("$uptoFirstDelimiter --- remainder: $remainder") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM