본문 바로가기
Swift

Swift에서 Zero Width Space 제거하기

by mr.conan 2024. 1. 22.
728x90
반응형

안녕하세요! 오늘은 Swift 언어에서 Zero Width Space를 제거하는 방법에 대해 알아보겠습니다. Zero Width Space는 텍스트에서 공백처럼 보이지만, 길이가 0으로 실제로는 공백이 아닌 문자입니다. 때때로 이러한 문자가 문자열에 포함되어 있으면 예상치 못한 동작을 일으킬 수 있습니다. 그러니 이를 제거하는 방법을 살펴보도록 하겠습니다.

1. 정규 표현식 사용

Swift에서 정규 표현식을 사용하여 Zero Width Space를 제거하는 방법이 있습니다. 다음은 간단한 예제 코드입니다.

import Foundation

func removeZeroWidthSpace(input: String) -> String {
    return input.replacingOccurrences(of: "\u{200B}", with: "")
}

// 사용 예시
let stringWithZeroWidthSpace = "안녕하세요\u{200B} Swift"
let stringWithoutZeroWidthSpace = removeZeroWidthSpace(input: stringWithZeroWidthSpace)

print(stringWithoutZeroWidthSpace)

 

위 코드에서 \u{200B}는 Zero Width Space의 유니코드입니다. replacingOccurrences(of:with:) 함수를 사용하여 해당 문자를 빈 문자열로 대체하여 제거할 수 있습니다.

2. 문자열 필터링

또 다른 방법은 문자열 필터링을 사용하는 것입니다. 아래 예제 코드를 참고해주세요.

func removeZeroWidthSpace(input: String) -> String {
    let filteredString = input.filter { $0 != "\u{200B}" }
    return String(filteredString)
}

// 사용 예시
let stringWithZeroWidthSpace = "안녕하세요\u{200B} Swift"
let stringWithoutZeroWidthSpace = removeZeroWidthSpace(input: stringWithZeroWidthSpace)

print(stringWithoutZeroWidthSpace)

 

filter 함수를 사용하여 문자열에서 Zero Width Space를 필터링합니다.

이렇게 두 가지 방법으로 Swift에서 Zero Width Space를 제거할 수 있습니다. 원하는 방법을 선택하여 사용하시면 됩니다. 코드를 통해 예제를 따라해보면 더 쉽게 이해할 수 있을 것입니다. 감사합니다!

728x90
반응형