swift는 String에 트림 방법이 있습니까?
swift는 String에 트림 방법이 있습니까? 예를 들면 다음과 같습니다.
let result = " abc ".trim()
// result == "abc"
의 시작과 끝에서 모든 공백을 제거하는 방법은 다음과 같습니다 String
.
(예는 Swift 2.0으로 테스트되었습니다 .)
let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
// Returns "Let's trim all the whitespace"
(예는 Swift 3+로 테스트되었습니다 .)
let myString = " \t\t Let's trim all the whitespace \n \t \n "
let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
// Returns "Let's trim all the whitespace"
도움이 되었기를 바랍니다.
이 코드를 Utils.swift와 같은 프로젝트의 파일에 넣으십시오.
extension String
{
func trim() -> String
{
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
}
그래서 당신은 이것을 할 수 있습니다 :
let result = " abc ".trim()
// result == "abc"
스위프트 3.0 솔루션
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: NSCharacterSet.whitespaces)
}
}
그래서 당신은 이것을 할 수 있습니다 :
let result = " Hello World ".trim()
// result = "HelloWorld"
스위프트 3.0
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
그리고 당신은 전화 할 수 있습니다
let result = " Hello World ".trim() /* result = "Hello World" */
스위프트 5 & 4.2
let trimmedString = " abc ".trimmingCharacters(in: .whitespaces)
//trimmedString == "abc"
스위프트 3
let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)
예, 다음과 같이 할 수 있습니다.
var str = " this is the answer "
str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print(srt) // "this is the answer"
CharacterSet은 실제로 .whitespacesAndNewlines와 같이 미리 정의 된 세트보다 훨씬 융통성이있는 트림 규칙을 생성 할 수있는 강력한 도구입니다.
예를 들어 :
var str = " Hello World !"
let cs = CharacterSet.init(charactersIn: " !")
str = str.trimmingCharacters(in: cs)
print(str) // "Hello World"
https://bit.ly/JString 쓴 Swift String 확장에서 trim () 메서드를 사용할 수 있습니다 .
var string = "hello "
var trimmed = string.trim()
println(trimmed)// "hello"
문자열을 특정 길이로 자르기
문장 / 텍스트 블록을 입력하고 텍스트에서 지정된 길이 만 저장하려는 경우. 클래스에 다음 확장명 추가
extension String {
func trunc(_ length: Int) -> String {
if self.characters.count > length {
return self.substring(to: self.characters.index(self.startIndex, offsetBy: length))
} else {
return self
}
}
func trim() -> String{
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
사용하다
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
//str is length 74
print(str)
//O/P: Lorem Ipsum is simply dummy text of the printing and typesetting industry.
str = str.trunc(40)
print(str)
//O/P: Lorem Ipsum is simply dummy text of the
또 다른 비슷한 방법 :
extension String {
var trimmed:String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
사용하다:
let trimmedString = "myString ".trimmed
extension String {
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
이 리포지토리에서 가져온 것 : https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206
Swift3 XCode 8 Final에서
(가) 통지 CharacterSet.whitespaces
더 이상 기능을하지 않습니다!
(아니요 NSCharacterSet.whitespaces
)
extension String {
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
자르려는 문자를 보낼 수도 있습니다.
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
func trim(characterSet:CharacterSet) -> String {
return self.trimmingCharacters(in: characterSet)
}
}
validationMessage = validationMessage.trim(characterSet: CharacterSet(charactersIn: ","))
// Swift 4.0 공백과 줄 바꾸기
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
문자열을 입력하고 모든 문자로 잘린 문자열 목록을 반환하는이 함수를 만들었습니다.
func Trim(input:String, character:Character)-> [String]
{
var collection:[String] = [String]()
var index = 0
var copy = input
let iterable = input
var trim = input.startIndex.advancedBy(index)
for i in iterable.characters
{
if (i == character)
{
trim = input.startIndex.advancedBy(index)
// apennding to the list
collection.append(copy.substringToIndex(trim))
//cut the input
index += 1
trim = input.startIndex.advancedBy(index)
copy = copy.substringFromIndex(trim)
index = 0
}
else
{
index += 1
}
}
collection.append(copy)
return collection
}
스위프트 에서이 작업을 수행 할 수있는 방법을 찾지 못 했으므로 (swift 2.0에서 컴파일하고 완벽하게 작동)
잊지 마세요 import Foundation
나 UIKit
.
import Foundation
let trimmedString = " aaa "".trimmingCharacters(in: .whitespaces)
print(trimmedString)
결과:
"aaa"
그렇지 않으면 얻을 것이다 :
error: value of type 'String' has no member 'trimmingCharacters'
return self.trimmingCharacters(in: .whitespaces)
참고 URL : https://stackoverflow.com/questions/26797739/does-swift-have-a-trim-method-on-string
'Programing' 카테고리의 다른 글
Node.js가있는 MySQL (0) | 2020.02.27 |
---|---|
Express.js-app.listen 및 server.listen (0) | 2020.02.27 |
Swift의 URL에서 이미지로드 / 다운로드 (0) | 2020.02.26 |
C # 또는 .NET에서 최악의 문제는 무엇입니까? (0) | 2020.02.26 |
16 진 숫자 앞에 0x가 붙는 이유는 무엇입니까? (0) | 2020.02.26 |