연습장/프로그래머스
프로그래머스(Kotlin)_ 김서방 찾기
아이른
2024. 3. 6. 09:54
1. String.indexOf()_ 문자열 찾기
- str.indexOf(S) : 문자열(str) 내에서 1번째 특정 문자(S)의 인덱스 반환
- str.indexOf(S, 3) : 문자열(str) 내에서 3번째 특정 문자(S)의 인덱스 반환
- str.lastindex(S) : 문자열(str) 내에서 마지막 특정 문자(S)의 인덱스 반환
class Solution {
fun solution(seoul: Array<String>): String {
retrun "김서방은 ${seoul.indexOf("Kim")}에 있다"
}
}
class Solution {
fun solution(seoul: Array<String>): String = "김서방은 ${seoul.indexOf("Kim")}에 있다"
}
2. 반복문과 indices : 배열 또는 리스트 반복문에서 실제 데이터 값을 인덱스 값으로 이용하고 싶을 때 사용
class Solution {
fun solution(seoul: Array<String>): String {
var answer = ""
for(i in seoul.indices){
if(seoul[i] == "Kim")
answer = "김서방은 ${i}에 있다"
}
return answer
}
}
3. forEachIndexed
fun main() {
val list = arrayListOf("a","b","c")
list.forEachIndexed {index, name ->
println("$index : $name")
}
}
//print
0 : a
1 : b
2 : c
- forEach : 배열 또는 리스트 반복문에서 리스트 안에 있는 값을 인자로 받아 사용
- forEachIndexed : forEach와 동일하지만 인덱스를 추가로 사용
class Solution {
fun solution(seoul: Array<String>): String {
seoul.forEachIndexed{i, name ->
if(name == "Kim")
return "김서방은 ${i}에 있다"
}
return "김서방은 없다"
}
}