[Swift][프로그래머스] 옹알이(2) - replacingOccurrences(of:with:)

팔랑이·2024년 6월 7일
0

iOS/Swift

목록 보기
24/71
post-thumbnail

프로그래머스: 옹알이 - 앞 게시물에서 이어집니다


replacingOccurrences(of:with:) 메서드

: 문자열 내의 특정 문자열을 모두 찾아 다른 문자열을 교체해서 반환하는 메서드. "aya", "ye", "woo", "ma" 를 각각 다른 문자나 숫자로 치환하고, 치환된 값에 바로 반복되는 부분이 있는지만 체크하면 된다. 이렇게 쉬운 방법이 있었다니...

우선 메서드 사용법을 알아보자.

기본 사용법

전체 교체

기본적으로 문자열 내에서 일치하는 모든 부분 문자열을 교체한다. 만약 특정 부분만 교체하고 싶다면 다른 방법이나 추가적인 방법이 필요하다.

let originalString = "Hello, world! Hello, Swift!"
let replacedString = originalString.replacingOccurrences(of: "Hello", with: "Hi")
print(replacedString) // 출력: Hi, world! Hi, Swift!

대소문자 구분 없이 교체

기본적으로 replacingOccurrences(of:with:)는 대소문자를 구분하며, 대소문자 구분 없이 교체하려면 options 매개변수를 사용하여 해결

대소문자 구분하여 교체

let caseText = "Hello, Playground! hello, playground!"
let newCaseText = caseText.replacingOccurrences(of: "hello", with: "Hi")
print(newCaseText) // 출력: Hello, Playground! Hi, playground!

대소문자 구분 없이 교체

let originalString = "Hello, world! hello, Swift!"
let replacedString = originalString.replacingOccurrences(of: "hello", with: "Hi", options: .caseInsensitive)
print(replacedString) // 출력: Hi, world! Hi, Swift!

replacingOccurrences(of:with:) 메서드를 사용한 풀이

이게 진짜 훨씬 머리 안아프고 안귀찮다!!!

func solution(_ babbling: [String]) -> Int {
    let can = ["aya", "ye", "woo", "ma"]
    var newArr = babbling
    var count = 0

    for (idx, i) in newArr.enumerated() {
        var newWord = i
        for (jidx, j) in can.enumerated() {
            newWord = newWord.replacingOccurrences(of:j, with: String(jidx))
        }
        newArr[idx] = newWord
    }
    
    for k in newArr {
        guard let test = Int(k) else {
            continue
        }
        if !k.contains("00") && !k.contains("11") && !k.contains("22") && !k.contains("33") {
            count += 1
        }
    }
    return count
}
profile
정체되지 않는 성장

0개의 댓글