source

Swift String의 문자를 대체할 수 있는 방법이 있나요?

myloves 2023. 4. 19. 00:42

Swift String의 문자를 대체할 수 있는 방법이 있나요?

Swift Swift의 을 찾고 .String.

예: "이것은 내 문자열입니다"

"This+is+my+string"을 "+"로 대체하고 싶습니다.

어떻게 하면 좋을까요?

이 답변은 Swift 4 및 5에 대해 업데이트되었습니다.아직 Swift 1, 2 또는 3을 사용 중인 경우 수정 내역을 참조하십시오.

몇 가지 옵션이 있습니다.@jaumard가 제안하는 대로 사용하여replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

알 수 @cprcrack은 @cprcrack입니다.options ★★★★★★★★★★★★★★★★★」range파라미터는 옵션이기 때문에 문자열 비교 옵션 또는 치환을 수행할 범위를 지정하지 않으면 다음 항목만 필요합니다.

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

이렇게일 경우 때 수 .components().join()지정된 구분 기호와 함께 다시 결합하는 함수입니다.

let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")

또는 NSString의 API를 사용하지 않는 보다 Swifty 솔루션을 찾고 있다면 이것을 사용할 수 있습니다.

let aString = "Some search text"

let replaced = String(aString.map {
    $0 == " " ? "+" : $0
})

다음을 사용할 수 있습니다.

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

이 확장 방식을 코드의 임의의 위치에 추가할 경우:

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

스위프트 3:

extension String
{
    func replace(target: String, withString: String) -> String
    {
        return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
    }
}

Swift 3, Swift 4, Swift 5 솔루션

let exampleString = "Example string"

//Solution suggested above in Swift 3.0
let stringToArray = exampleString.components(separatedBy: " ")
let stringFromArray = stringToArray.joined(separator: "+")

//Swiftiest solution
let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")

테스트해 본 적이 있습니까?

var test = "This is my string"

let replaced = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)
var str = "This is my string"

print(str.replacingOccurrences(of: " ", with: "+"))

출력은

This+is+my+string

스위프트 5.5

이 내선번호를 사용하고 있습니다.

extension String {

    func replaceCharacters(characters: String, toSeparator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        let components = components(separatedBy: characterSet)
        let result = components.joined(separator: toSeparator)
        return result
    }

    func wipeCharacters(characters: String) -> String {
        return self.replaceCharacters(characters: characters, toSeparator: "")
    }
}

사용방법:

"<34353 43434>".replaceCharacters(characters: "< >", toSeparator:"+") // +34353+43434+
"<34353 43434>".wipeCharacters(characters: "< >") // 3435343434

Swift 4:

let abc = "Hello world"

let result = abc.replacingOccurrences(of: " ", with: "_", 
    options: NSString.CompareOptions.literal, range:nil)

print(result :\(result))

출력:

result : Hello_world

Sunkas와 유사한 Swift 3 솔루션:

extension String {
    mutating func replace(_ originalString:String, with newString:String) {
        self = self.replacingOccurrences(of: originalString, with: newString)
    }
}

용도:

var string = "foo!"
string.replace("!", with: "?")
print(string)

출력:

foo?

기존 가변 문자열을 수정하는 카테고리:

extension String
{
    mutating func replace(originalString:String, withString newString:String)
    {
        let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
        self = replacedString
    }
}

용도:

name.replace(" ", withString: "+")

Ramis의 답변을 바탕으로 한 Swift 3 솔루션:

extension String {
    func withReplacedCharacters(_ characters: String, by separator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        return components(separatedBy: characterSet).joined(separator: separator)
    }
}

Swift 3 명명 규칙에 따라 적절한 함수 이름을 생각해 내려고 했습니다.

요.그냥 (단어 또는 문자)를 바꾸고 싶을 뿐이에요.String

저는 ★★★★★★★★★★★★★★★★★★★★★★★★★★.Dictionary

  extension String{
    func replace(_ dictionary: [String: String]) -> String{
          var result = String()
          var i = -1
          for (of , with): (String, String)in dictionary{
              i += 1
              if i<1{
                  result = self.replacingOccurrences(of: of, with: with)
              }else{
                  result = result.replacingOccurrences(of: of, with: with)
              }
          }
        return result
     }
    }

사용.

let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999

Xcode 11 • Swift 5.1

StringProtocol의 .replacingOccurrences같이 할 수 .

extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
        self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
    }
}

var name = "This is my string"
name.replaceOccurrences(of: " ", with: "+")
print(name) // "This+is+my+string\n"
var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)

4.요. swift 4.2를 쓰면 요.replacingOccurrences(of: " ", with: "_")

var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)

2 로는 '2'String 하지 않게 .SequenceTypeㄴ, ㄴ, ㄴ, 이 할 수 for...inloopsyslog.syslog..syslog.

입니다.String로로 합니다.Array다음과 같이 지수의 이점을 얻을 수 있습니다.

let input = Array(str)

String을 사용하다저는 원하는 결과를 내놓지 못하고 좌절해서 포기하려고 했어요.그러나, 독자적인 회피책을 작성했습니다.하다

extension String {
    subscript (_ index: Int) -> String {
    
        get {
             String(self[self.index(startIndex, offsetBy: index)])
        }
    
        set {
            remove(at: self.index(self.startIndex, offsetBy: index))
            insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
        }
    }
}

이제 원래 원하는 대로 인덱스를 사용하여 문자열에서 단일 문자를 읽고 바꿀 수 있습니다.

var str = "cat"
for i in 0..<str.count {
 if str[i] == "c" {
   str[i] = "h"
 }
}

print(str)

Swift's String 액세스 모델을 사용하여 사용하기 쉽고 유용한 방법입니다.이제 당신은 다음 번에 현을 그대로 통과시킬 수 있을 때, 그것을 던져넣지 않고, 그것은 부드러운 항해라고 느낄 것입니다.Array.

시험해 보고 도움이 되는지 확인해 보세요!

매우 심플한 기능을 실장난은, 다음과 같습니다.

func convap (text : String) -> String {
    return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}

다음과 같이 쓸 수 있습니다.

let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')

Regex가 가장 유연하고 확실한 방법이라고 생각합니다.

var str = "This is my string"
let regex = try! NSRegularExpression(pattern: " ", options: [])
let output = regex.stringByReplacingMatchesInString(
    str,
    options: [],
    range: NSRange(location: 0, length: str.characters.count),
    withTemplate: "+"
)
// output: "This+is+my+string"

빠른 확장:

extension String {

    func stringByReplacing(replaceStrings set: [String], with: String) -> String {
        var stringObject = self
        for string in set {
            stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
        }
        return stringObject
    }

}

사용법은 다음과 같습니다.let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")

기능의 속도는 자랑할 수 없는 것이지만, 당신은 일련의 기능을 통과할 수 있습니다.String한 번에 두 개 이상의 대체품을 만들 수 있습니다.

다음으로 Swift 3의 예를 나타냅니다.

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
} 

다음은 인플레이스 오카렌스 치환 방법에 대한 확장입니다.String불필요한 복사를 하지 않고 모든 작업을 수행할 수 있습니다.

extension String {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
        var range: Range<Index>?
        repeat {
            range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
            if let range = range {
                self.replaceSubrange(range, with: replacement)
            }
        } while range != nil
    }
}

(메서드 시그니처도 빌트인의 시그니처를 모방하고 있습니다.String.replacingOccurrences()방식)

다음과 같은 방법으로 사용할 수 있습니다.

var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"

Objective-C를 사용하지 않을 경우NSStringmethods를 사용하면 됩니다.split그리고.join:

var string = "This is my string"
string = join("+", split(string, isSeparator: { $0 == " " }))

split(string, isSeparator: { $0 == " " })문자열 배열을 반환합니다(["This", "is", "my", "string"]).

join이 요소들을 a와 결합하다+그 결과, 다음과 같이 출력됩니다."This+is+my+string".

테스트할 수 있습니다.

newString = test.stringByReplacingOccurrencesOfString(" " " ", string: "+", 옵션: 0, 범위: 0)

스위프트 5.5

그러나 이전 버전에서는 작동할 수 있습니다.

공백이나 -를 _와 같은 것으로 대체하고 싶어서 자주 교체합니다.이 문자열 확장자를 사용하면 그렇게 할 수 있습니다.

extension String {
    func removingCharacters(_ characters:CharacterSet) -> Self {
        Self(self.unicodeScalars.filter {
            !characters.contains($0)
        })
    }
    func removingCharacters(in string:String) -> Self {
        Self(self.unicodeScalars.filter {
            !CharacterSet(charactersIn:string).contains($0)
        })
    }
    
    func replacingCharacters(_ characters:CharacterSet, with newChar:Character) -> Self {
        String(self.compactMap( {
            CharacterSet(charactersIn: "\($0.1)").isSubset(of: characters)
             ? newChar : $0.1
        }))
    }
    
    func replacingCharacters(in string:String, with newChar:Character) -> Self {
        String(self.compactMap( {
            CharacterSet(charactersIn: "\($0)").isSubset(of: CharacterSet(charactersIn:string))
             ? newChar : $0
        }))
    }
}

사용방법:

print("hello \n my name\t is Joe".removingCharacters(.whitespacesAndNewlines))
print("hello \n my name\t is Joe".removingCharacters(in: " \t\n"))

print("ban annan anann ana".replacingCharacters(.whitespacesAndNewlines, with: "_"))
print("ban-annan anann ana".replacingCharacters(in: " -", with: "_"))

분명히 한 명의 캐릭터에게는.replacingOccurrences(of: " ", with: "+")더 좋아요.

퍼포먼스 비교는 하지 않았습니다.

let toArray = aString.components(separatedBy: characterSet)
let backToString = toArray.joined(separator: "+") 

라미스의 확장자로 한 스타일입니다.누가 해줬으면 좋겠어요.

https://stackoverflow.com/a/63416058/5946596의 이모티콘 교체도 참조하십시오.

부터 iOS 16 이번에는 새로운 을 쓸 수 것 같아요.RangeReplaceableCollection replace(_:with:maxReplacements:), 는 를 사용합니다.Regex파라미터를 지정하여 요청을 맞춤화할 수 있습니다.

var myString = "This is my string"
myString.replace(" ", with: "+")

말고 꼭 해 주세요.import RegexBuilder을 유효하게 하기

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