programing

Swift-문자열에서 "문자 제거

nasanasas 2020. 11. 22. 19:50
반응형

Swift-문자열에서 "문자 제거


"Optional ("5 ")"문자열이 있습니다. 5. 주변의 ""를 제거해야합니다. 다음을 수행하여 '옵션'을 제거했습니다.

text2 = text2.stringByReplacingOccurrencesOfString("Optional(", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

코드에서 문자열의 끝을 지정하기 때문에 "문자를 제거하는 데 어려움이 있습니다.


Swift는 백 슬래시를 사용하여 큰 따옴표를 이스케이프합니다. 다음은 Swift에서 이스케이프 된 특수 문자 목록입니다.

  • \0 (널 문자)
  • \\ (백 슬래시)
  • \t (가로 탭)
  • \n (줄 바꿈)
  • \r (캐리지 리턴)
  • \" (큰 따옴표)
  • \' (작은 따옴표)

이것은 작동합니다.

text2 = text2.replacingOccurrences(of: "\\", with: "", options: NSString.CompareOptions.literal, range: nil)

Swift 3 및 Swift 4 :

text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)

Swift 3.0.1로 업데이트 된 최신 문서는 다음과 같습니다.

  • 널 문자 ( \0)
  • 백 슬래시 ( \\)
  • 가로 탭 ( \t)
  • 줄 바꿈 ( \n)
  • 캐리지 리턴 ( \r)
  • 큰 따옴표 ( \")
  • 작은 따옴표 ( \')
  • 유니 코드 스칼라 ( \u{n}). 여기서 n은 1-8 개의 16 진수입니다.

더 자세한 정보가 필요하면 여기 에서 공식 문서를 볼 수 있습니다.


다음은 신속한 3 업데이트 답변입니다.

var editedText = myLabel.text?.replacingOccurrences(of: "\"", with: "")
Null Character (\0)
Backslash (\\)
Horizontal Tab (\t)
Line Feed (\n)
Carriage Return (\r)
Double Quote (\")
Single Quote (\')
Unicode scalar (\u{n})

옵션을 제거하려면이 작업 만 수행해야합니다.

println("\(text2!)")

"!"를 사용하지 않으면 text2의 선택적 값을받습니다.

그리고 5에서 ""를 제거하려면 NSInteger 또는 NSNumber 쉽게 변환해야합니다. ""가 있으면 문자열이됩니다.


나는 결국 이것을 놀이터에서 작동시켜 문자열에서 제거하려고하는 여러 문자를 가지고 있습니다.

var otherstring = "lat\" : 40.7127837,\n"
var new = otherstring.stringByTrimmingCharactersInSet(NSCharacterSet.init(charactersInString: "la t, \n \" ':"))
count(new) //result = 10
println(new) 
//yielding what I'm after just the numeric portion 40.7127837

Martin R이 말했듯이 "Optional ("5 ")"문자열은 뭔가 잘못한 것처럼 보입니다.

dasblinkenlight가 대답하므로 괜찮습니다. 그러나 향후 독자를 위해 대체 코드를 다음과 같이 추가하려고합니다.

if let realString = yourOriginalString {
    text2 = realString
} else {
    text2 = ""
}

text2 in your example looks like String and it is maybe already set to "" but it looks like you have an yourOriginalString of type Optional(String) somewhere that it wasn't cast or use correctly.

I hope this can help some reader.


If you want to remove more characters for example "a", "A", "b", "B", "c", "C" from string you can do it this way:

someString = someString.replacingOccurrences(of: "[abc]", with: "", options: [.regularExpression, .caseInsensitive])

You've instantiated text2 as an Optional (e.g. var text2: String?). This is why you receive Optional("5") in your string. take away the ? and replace with:

var text2: String = ""

Let's say you have a string:

var string = "potatoes + carrots"

And you want to replace the word "potatoes" in that string with "tomatoes"

string = string.replacingOccurrences(of: "potatoes", with: "tomatoes", options: NSString.CompareOptions.literal, range: nil)

If you print your string, it will now be: "tomatoes + carrots"

If you want to remove the word potatoes from the sting altogether, you can use:

string = string.replacingOccurrences(of: "potatoes", with: "", options: NSString.CompareOptions.literal, range: nil)

If you want to use some other characters in your sting, use:

  • Null Character (\0)
  • Backslash (\)
  • Horizontal Tab (\t)
  • Line Feed (\n)
  • Carriage Return (\r)
  • Double Quote (\")
  • Single Quote (\')

Example:

string = string.replacingOccurrences(of: "potatoes", with: "dog\'s toys", options: NSString.CompareOptions.literal, range: nil)

Output: "dog's toys + carrots"


If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:

if let value = text {
    print(value)
}

Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.

참고URL : https://stackoverflow.com/questions/25591241/swift-remove-character-from-string

반응형