# Kotlin Split String / List ###### tags: `Kotlin` `Split` # Split String ## Reference: * [Kotlin Split String example](http://kotlination.com/kotlin/kotlin-split-string-example) * [Kotlin – Split String to Lines – String.lines() function](https://www.tutorialkart.com/kotlin/split-string-to-lines/) ### 1. split() with Regex This overload of split() method requires a value of Regex type, not String: ``` inline fun CharSequence.split(regex: Regex, limit: Int = 0): List<String> ``` Kotlin not only uses the same regular expression syntax and APIs as Java, but also has extension function toRegex() to convert a string into a regular expression. example: ``` val str = "Kotlination.com = Be Kotlineer - Be Simple - Be Connective" val separate1 = str.split("=|-".toRegex()) println(separate1) ``` Result: ``` [Kotlination.com , Be Kotlineer , Be Simple , Be Connective] ``` ### 2. split() with plain-text characters/strings Instead of using Regex, you can specify character/string arguments: ``` fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> ``` example: ``` val str = "Kotlination.com = Be Kotlineer - Be Simple - Be Connective" val separate2 = str.split(" = "," - ") println(separate2) ``` Result: ``` [Kotlination.com, Be Kotlineer, Be Simple, Be Connective] ``` ### 3 ``lines()`` ``` fun CharSequence.lines(): List<String> ``` example: ``` // string to be split to lines val str: String = "Kotlin Tutorial.\nLearn Kotlin Programming with Ease.\rLearn Kotlin Basics." // splitting string using lines() function val lines = str.lines() // printing lines lines.forEach { println(it) } ``` Result: ``` Kotlin Tutorial. Learn Kotlin Programming with Ease. Learn Kotlin Basics. ``` --- # [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin/split-list-into-parts) ## 1. Introduction Let’s say we have an array like ``[a, b, c, d, e, f]`` and we want to split the elements up into separate groups, like ``` [[a, b], [c, d], [e, f]] or [[a, b, c], [d], [e,f]]. ``` In this tutorial, we’ll achieve this while examining some differences between Kotlin’s ``groupBy``, ``chunked``, and ``windowed``. ## 2. Splitting a List Into a List of Pairs For our examples, we’ll use two lists – one with an even number of elements and one with an odd number of elements: ``` val evenList = listOf(0, "a", 1, "b", 2, "c"); val unevenList = listOf(0, "a", 1, "b", 2, "c", 3); ``` Clearly, we can divide our evenList into exactly three pairs. However, our ``unevenList`` will __have one extra element__. In the remainder of this section, we’ll see various implementations for splitting our two lists, including __how they deal with the extra element in ``unevenList``__. ### 2.4. Using chunked But, we can do this more elegantly with chunked. So, let’s apply the method to our evenList: ``` evenList.chunked(2) ``` The ``evenList`` provides us with the pairs we want: ``` [[0, "a"], [1, "b"], [2, "c"]] ``` While the ``unevenList`` gives us the pairs and the extra element: ``` [[0, "a"], [1, "b"], [2, "c"], [3]] ``` ### 2.5. Using ``windowed`` And ``chunked`` works really well, __but sometimes we need a bit more control__. For instance, we may need to specify if we want only pairs, or if we want to include the extra element. The ``windowed`` method provides us with a ``partialWindows`` ``Boolean``, which indicates if we want the partial result or not. __By default, ``partialWindows`` is ``false``__. So, the following statements produce the same result: ``` evenList.windowed(2, 2) unevenList.windowed(2, 2, false) ``` Both return the list without the separate element: ``` [[0, "a"], [1, "b"], [2, "c"]] ``` Finally, when we set ``partialWindows`` to ``true`` to include the partial result: ``` unevenList.windowed(2, 2, true) ``` We’ll get the list of pairs plus the separate element: ``` [[0, "a"], [1, "b"], [2, "c"], [3]] ``` 看 Source code, ``chunked()`` 其實是引用 ``windowed()`` ``` public fun <T> Iterable<T>.chunked(size: Int): List<List<T>> { return windowed(size, size, partialWindows = true) } ``` ## 3. A Few Words About the ``partition()`` Function We’ve solved our problem using ``groupBy()``, ``chunked()``, and ``windowed()``. ``partition()`` is another function that can split a list into parts. As such, it can be pretty convenient for solving some similar problems. Kotlin’s ``partition()`` function can split a list into a pair of two lists by a given predicate function. An example can clarify this quickly. Let’s say we have a list of unsorted integers and we’d like to split it into two lists – one containing numbers less than ``42``, and the other holding numbers greater than or equal to ``42``. If we solve this problem using ``partition()``, it’s pretty easy: ``` val numbers = listOf(42, 1984, 1, 0, -4, 23, 100, 6, 8) val aPairOfList = numbers.partition { it < 42 } with(aPairOfList) { assertEquals(listOf(1, 0, -4, 23, 6, 8), first) assertEquals(listOf(42, 1984, 100), second) } ``` As the example above shows, we provided ``it < 42`` as the predicate function. In the resulting pair, the first list carries all elements for which the predicate function yielded ``true``, and the second list holds elements for which the predicate function returns ``false``. Sometimes, we want to use the split lists as variables directly instead of using them like ``thePair.first`` and ``thePair.second``. In this case, we can use a deconstructing declaration to assign ``partition()``‘s result to two list variables in one shot: ``` val (lessThan42, greaterThanOrEq42) = numbers.partition { it < 42 } assertEquals(listOf(1, 0, -4, 23, 6, 8), lessThan42) assertEquals(listOf(42, 1984, 100), greaterThanOrEq42) ``` 原來 kotlin 愈來愈像 python