Programming/Kotlin

[Kotlin] ์ฝ”ํ‹€๋ฆฐ ๋ฌธ์ž์—ด ๊ต์ฒดํ•˜๊ธฐ / ๋ฌธ์ž์—ด์˜ ํŠน์ • ์ธ๋ฑ์Šค์— ๋ฌธ์ž ๋ฐ”๊พธ๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 1. 16. 23:58
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” ์ฝ”ํ‹€๋ฆฐ ๋ฌธ์ž์—ด (string)์˜ ํŠน์ • ์ธ๋ฑ์Šค ๋ฌธ์ž ๋ฐ”๊พธ๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to do 

์ธ๋ฑ์Šค ๋ฌธ์ž ๋ฐ”๊พธ๋Š” ๋งŽ์€ ๋ฐฉ๋ฒ•์ด ์žˆ๊ฒ ์ง€๋งŒ, ์ €๋Š” substring() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ง„ํ–‰ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

์•„๋ž˜์™€ ๊ฐ™์ด "20230116"์ด๋ผ๋Š” ๋ฌธ์ž์—ด์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. ์—ฌ๊ธฐ์„œ ์ธ๋ฑ์Šค 4 ์œ„์น˜์— "12"๋กœ ๋ฐ”๊พธ๊ธฐ ์œ„ํ•ด ์•„๋ž˜์™€ ๊ฐ™์ด ๊ตฌํ˜„ํ•˜์˜€์Šต๋‹ˆ๋‹ค. substring() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ต์ฒดํ•  ๋ฌธ์ž๋ฅผ ๋ถ„๋ฆฌํ•˜๊ณ , + ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ๋‚˜๋จธ์ง€ ๋ฌธ์ž์—ด์„ ๋”ํ•ด์ค๋‹ˆ๋‹ค. println()์„ ํ†ตํ•ด ๋‚˜์˜จ ๊ฒฐ๊ณผ๋Š” "20231216" ์ž…๋‹ˆ๋‹ค. "01"์ด "12"๋กœ ์ž˜ ๋ฐ”๋€Œ์–ด ๋™์ž‘ํ•˜๊ณ  ์žˆ๋„ค์š” :) 

fun main() {
    var string = "20230116"
    val char = "12"
    val index = 4
    string = string.substring(0, index) + char + string.substring(index + 2)
    println(string)   // 20231216  
}
๋ฐ˜์‘ํ˜•