Kotlin

์ฝ”ํ‹€๋ฆฐ Kotlin split("")์ด ์ œ๋Œ€๋กœ ๋™์ž‘ํ•˜์ง€ ์•Š๋Š” ์ด์œ 

๋…ธ๋ฃจ๋ฃฝ 2023. 12. 3. 19:15

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฌธ์ž์—ด ๋Œ๋ฆฌ๊ธฐ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.0 ๋ฌธ์ œ๋ฅผ ํ’€๋ฉฐ ์ž์กด๊ฐ์„ ์˜ฌ๋ฆฌ๊ณ  ์žˆ๋˜ ๋„์ค‘, split ํ•จ์ˆ˜์— ๋Œ€ํ•œ ๋†€๋ผ์šด ์‚ฌ์‹ค(?)์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค.

 

๋ฐœ๊ฒฌํ•˜๊ฒŒ ๋œ ๋ฌธ์ œ๋Š” '๋ฌธ์ž์—ด ๋Œ๋ฆฌ๊ธฐ'๋ผ๋Š” ๋ฌธ์ œ๋‹ค.

https://school.programmers.co.kr/learn/courses/30/lessons/181945

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

'split์œผ๋กœ ๋ฌธ์ž์—ด์„ ์ชผ๊ฐœ์„œ map์„ ์‚ฌ์šฉํ•˜๋ฉด ๋˜๊ฒ ๊ตฐ..'์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์งฐ๋‹ค.

fun main(args: Array<String>) {
    readLine()!!.split("").map { println(it) }
}

 

ํ•˜

์ง€

๋งŒ

 

.....์‘?

 

๋งž์™œํ‹€!!!!!!๋ฌด์ƒˆ๊ฐ€ ๋˜์–ด์„œ REPL์— ์ด๊ฒƒ์ €๊ฒƒ ์‹คํ—˜ํ•ด ๋ณธ ๊ฒฐ๊ณผ,,

 

๋งจ์•ž, ๋งจ๋’ค์— ๊ณต๋ฐฑ ๋ฌธ์ž์—ด์ด ๋“ค์–ด๊ฐ„๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ๋˜์—ˆ๋‹ค..!๐Ÿ˜ฎ

 

๋ฌธ์ œ์˜ ์›์ธ์€ ์ฐพ์•˜๋Š”๋ฐ,

๋„๋Œ€์ฒด ์™œ ์ด๋Ÿฐ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ์ธ๊ฐ€......๐Ÿค”๊ฐ€ ๊ต‰์žฅํžˆ ๊ถ๊ธˆํ–ˆ๋‹ค.

ํญํ’ ์„œ์นญ ๋šœ๋“ค๋šœ๋“ค

 

 

 

 Kotlin split("") ์˜ ๋ฌธ์ œ์ 

์ •๋‹ต์€ ์ฝ”ํ‹€๋ฆฐ ๊ณต์‹ ๋ฌธ์„œ์— ์žˆ์—ˆ๋‹ค.

 

One or more strings....

 

splitํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์ธ delimiters๋Š” ๊ธธ์ด๊ฐ€ 1์ด์ƒ์ด์–ด์•ผ ํ–ˆ๋˜ ๊ฒƒ์ด์—ˆ๋‹ค.!

"" ์–˜๋Š” length๊ฐ€ 0์ด๋ผ์„œ ์„ ํ–‰, ํ›„ํ–‰ ๋ฌธ์ž์—ด์ด ์ œ๊ฑฐ๋˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ ๋‚˜์˜ค๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.

 

 

 

์ฆ‰, 

๊ทธ๋™์•ˆ ์‚ฌ์šฉํ•˜๋˜ ์ž๋ฐ”์˜ split("")์€ ์•ž๋’ค ๊ณต๋ฐฑ์„ ์•Œ์•„์„œ ์ œ๊ฑฐํ•ด ์ฃผ๋Š” ๊ฑฐ์˜€๋‹ค..

(์ž˜ ์ง€๋‚ด๋‹ˆ..? ์ž๋ฐ”์•ผ..?)

 

 

 

ํ•ด๊ฒฐ๋ฒ•

toCharArray() ๋ผ๋Š” ์•„์ฃผ ์ข‹์€ ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค..

๊ทธ๊ฑธ ์“ฐ๋ฉด ๋จ.

์•„๋‹ˆ๋ฉด filter๋กœ ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•˜๋ฉด ๋œ๋‹ค.

 

 

split ํ•จ์ˆ˜๊ฐ€ ๋งŒ๋“ค์–ด์ง„ ์˜๋„๋Š” ํŠน์ • ๋ฌธ์ž์—ด์„ ์‚ฌ์šฉํ•ด ๋ฐฐ์—ด๋กœ ๋‚˜๋ˆ„๊ธฐ ์œ„ํ•ด์„œ๋‹ˆ๊นŒ

๊ฐ์ž ํ•จ์ˆ˜์˜ ์˜๋„์™€ ๋ชฉ์ ์— ๋งž๊ฒŒ ์“ฐ๋„๋ก ํ•˜์ž!!!!! ํ•˜ํ•˜ํ•˜

 

 

 

Reference

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/split.html

 

split - Kotlin Programming Language

 

kotlinlang.org

https://stackoverflow.com/questions/70941592/why-does-kotlins-split-function-result-in-a-leading-and-trailing-empty-stri

 

Why does Kotlin's split("") function result in a leading and trailing empty string?

I'm a Java developer who tried Kotlin and found a counterintuitive case between these two languages. Consider the given code in Kotlin: "???".split("") # gives ["", &...

stackoverflow.com