[swift] 문자열에서 특정 단어 소문자로 변경하기

가령, “Hello, World! This is a Sample Sentence.” 라는 문자열에서 “sample” 단어를 소문자로 변경하고 싶다고 가정해 봅시다.

let str = "Hello, World! This is a Sample Sentence."
let wordToConvert = "Sample"

if let range = str.range(of: wordToConvert, options: .caseInsensitive) {
    let lowercaseWord = str[range].lowercased()
    let newString = str.replacingCharacters(in: range, with: lowercaseWord)
    print(newString)
} else {
    print("Word not found")
}

이 예제에서는 입력된 문자열에서 “Sample” 단어를 찾아서 소문자로 변경한 뒤, 변경된 문자열을 출력하게 됩니다.

이런 방식으로 ${swift}를 사용하여 입력된 문자열에서 특정 단어를 찾고, 해당 단어를 소문자로 변경하여 새로운 문자열을 생성할 수 있습니다.