본문 바로가기
카테고리 없음

Swift - String 문자 바꾸기 replace

by 둥둥동동# 2022. 6. 27.
728x90

 

String을 replace

 

Swift에서 특정 문자열을 대체하는 방법을 알아보겠습니다

 

 

 

 

1.문자로 대체하기

 

let s = "This is my string"
let modified = s.replaceMyString(" ", withString:"+")    
cs

 

String에 replaceMyString 메서드를 추가합니다

 

extension String
{
    func replaceMyString(target: String, withString: String-> String
    {
       return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }
}
cs

 

 

 

2.index로 대체하기

 

 

func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
    var chars = Array(myString)     // gets an array of characters
    chars[index] = newChar
    let modifiedString = String(chars)
    return modifiedString
}
 
print(replace(myString:"HaHaHa"3"e"))//HaHeHa
cs

문자의 연속된 데이터가 String임을 이용해 문자열을 배열로 만들어 index에 접근하는 방법입니다

 

 

 

3.NSString 메서드 활용

 

 

NSString은 replacingOccurrences(of: width:)메서드가 존재합니다

아래와 같이 활용할 수 있습니다

let str1 = "Hello! World"
let str2 = str1.replacingOccurrences(of: "!"with"♥︎")
print(str2) //Hello♥︎ World
cs

유니코드에서는 정확히 동작하지 않을 수 있습니다

 

 

 

 

참고자료

 

https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string

 

Any way to replace characters on Swift String?

I am looking for a way to replace characters in a Swift String. Example: "This is my string" I would like to replace " " with "+" to get "This+is+my+string". How can I achieve this?

stackoverflow.com

 

https://stackoverflow.com/questions/24789515/how-to-replace-nth-character-of-a-string-with-another

 

How to replace nth character of a string with another

How could I replace nth character of a String with another one? func replace(myString:String, index:Int, newCharac:Character) -> String { // Write correct code here return modifiedStrin...

stackoverflow.com

 

728x90

댓글