๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | mapIndexed

hyihyiยท2023๋…„ 12์›” 13์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
18/70
post-thumbnail

mapIndexed

์š”์†Œ์™€ ๊ทธ ์š”์†Œ์˜ ์ธ๋ฑ์Šค๋ฅผ ๋™์‹œ์— ์‚ฌ์šฉํ•ด์•ผ ํ•  ๋•Œ ์œ ์šฉ

fun Ex1(){
    val list = listOf("apple", "banana", "cherry")
    val result = list.mapIndexed { index, value -> "$index: $value" }
    println(result)
}

fun Ex2(){
    val numbers = listOf(1, 2, 3)
    val sumWithIndex = numbers.mapIndexed { index, value -> value + index }
    println(sumWithIndex)
}

fun Ex3(){
    val words = listOf("hello", "world", "kotlin", "programming")
    val upperCaseEven = words.mapIndexed { index, value -> if (index % 2 == 0) value.uppercase() else value }
    println(upperCaseEven)
}

fun Ex4(){
    val numbers2 = listOf(5, 10, 15, 20)
    val filteredMapped = numbers2.mapIndexedNotNull { index, value -> if (value % 10 == 0) index else null }
    println(filteredMapped)
}
[0: apple, 1: banana, 2: cherry]
[1, 3, 5]
[HELLO, world, KOTLIN, programming]
[1, 3]

โœŠ ๊ณต๋ฐฑ์œผ๋กœ ํ•ฉํ•ด์ง„ ๋ฌธ์ž์—ด์„ ๊ณต๋ฐฑ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ˆˆ ํ›„ ๊ฐ ๋ฌธ์ž๋ฅผ ์ชผ๊ฐœ๊ธฐ

//solution("aBcd EFG")
//1.aBcd๊ณผ EFG๋กœ ๋‚˜๋ˆ„๊ธฐ
//2.aBcd๋ฅผ a,B,c,d๋กœ ๋‚˜๋ˆ ์„œ ๊ฐ ์ธ๋ฑ์Šค๊ฐ€ ์ง์ˆ˜๋ฒˆ์งธ์ผ ๋•Œ ๋Œ€๋ฌธ์ž๋กœ ๋ฐ”๊พธ๊ธฐ

fun solution(s: String): String {
    var answer = ""
    val S = s.split(' ')
    val m = S.map { value->
        value.mapIndexed { index, c ->
            if(index % 2 == 0) c.uppercase() else c
        }.joinToString("")
    }.joinToString(" ")
    println(m)
    return answer
}
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

0๊ฐœ์˜ ๋Œ“๊ธ€