programing

Swift에서 문자열을 배열로 분할하시겠습니까?

subpage 2023. 4. 14. 21:43
반응형

Swift에서 문자열을 배열로 분할하시겠습니까?

여기에 문자열이 있다고 가정합니다.

var fullName: String = "First Last"

공백에 문자열 베이스를 분할하고 값을 각 변수에 할당하고 싶다.

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

또, 유저가 성을 가지지 않는 경우도 있습니다.

전화하세요.componentsSeparatedByString your 서 method on on のfullName

import Foundation

var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")

var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]

Swift 3+ 업데이트

import Foundation

let fullName    = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")

let name    = fullNameArr[0]
let surname = fullNameArr[1]

Swift를 입니다.split뭇매를 맞다

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

Swift 2 사용

Swift 2 swiftviewview Character View swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift swift2 。, 또는 , String SequenceType Collection을 .해 주세요. 'Protocols'를 ..characters "CharacterView" "CharacterView": CharacterView" 는 Collection (": CharacterView" SequenceType") 을 채택하고 .프로토콜)을 입력합니다.

let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last 

가장 쉬운 방법은 componentsSeparatedBy를 사용하는 것입니다.

Swift 2의 경우:

import Foundation
let fullName : String = "First Last";
let fullNameArr : [String] = fullName.componentsSeparatedByString(" ")

// And then to access the individual words:

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]

Swift 3의 경우:

import Foundation

let fullName : String = "First Last"
let fullNameArr : [String] = fullName.components(separatedBy: " ")

// And then to access the individual words:

var firstName : String = fullNameArr[0]
var lastName : String = fullNameArr[1]

Swift Dev. 4.0(2017년 5월 24일)

' ' ''splitSwift 4(베타)에 있습니다.

import Foundation
let sayHello = "Hello Swift 4 2017";
let result = sayHello.split(separator: " ")
print(result)

출력:

["Hello", "Swift", "4", "2017"]

값에 대한 액세스:

print(result[0]) // Hello
print(result[1]) // Swift
print(result[2]) // 4
print(result[3]) // 2017

Xcode 8.1 / Swift 3.0.1

어레이를 사용한 복수의 딜리미터는 다음과 같습니다.

import Foundation
let mathString: String = "12-37*2/5"
let numbers = mathString.components(separatedBy: ["-", "*", "/"])
print(numbers)

출력:

["12", "37", "2", "5"]

Swift 5.2 업데이트 및 가장 간단한 방법

let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])

이 인쇄물은

['밥', '히트', 'a', '공', 'the', 'hit', 'BALL', 'flew', 'far', 'after', 'was', 'hit', 'Hie', '어떻게', 'r', 'u', '']

다만, 빈 문자열을 필터링 하는 경우는,

let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})

산출량,

['밥', '히트', 'a', 'the', 'hit', 'BALL', 'flew', 'far', 'after', 'was', 'hit', 'Hie', '어떻게', 'r', 'u']

, Foundation은 Import 됩니다.

Swift 4 이후

사용자 이름의 형식만 올바르게 지정하면 PersonName ComponentsFormatter를 사용할 수 있습니다.

PersonNameComponentsFormatter 클래스는 PersonNameComponents 객체로 표현되는 사용자 이름의 구성 요소를 현지화한 표현으로 제공합니다.사용자에게 사용자 이름 정보를 표시할 때 현지화된 이름을 만들려면 이 클래스를 사용합니다.


// iOS (9.0 and later), macOS (10.11 and later), tvOS (9.0 and later), watchOS (2.0 and later)
let nameFormatter = PersonNameComponentsFormatter()

let name =  "Mr. Steven Paul Jobs Jr."
// personNameComponents requires iOS (10.0 and later)
if let nameComps  = nameFormatter.personNameComponents(from: name) {
    nameComps.namePrefix   // Mr.
    nameComps.givenName    // Steven
    nameComps.middleName   // Paul
    nameComps.familyName   // Jobs
    nameComps.nameSuffix   // Jr.

    // It can also be configured to format your names
    // Default (same as medium), short, long or abbreviated

    nameFormatter.style = .default
    nameFormatter.string(from: nameComps)   // "Steven Jobs"

    nameFormatter.style = .short
    nameFormatter.string(from: nameComps)   // "Steven"

    nameFormatter.style = .long
    nameFormatter.string(from: nameComps)   // "Mr. Steven Paul Jobs jr."

    nameFormatter.style = .abbreviated
    nameFormatter.string(from: nameComps)   // SJ

    // It can also be use to return an attributed string using annotatedString method
    nameFormatter.style = .long
    nameFormatter.annotatedString(from: nameComps)   // "Mr. Steven Paul Jobs jr."
}

여기에 이미지 설명 입력

편집/갱신:

Swift 5 이후

문자를 사용하지 않는 문자로 문자열을 분할하는 것만으로 새로운 문자 속성을 사용할 수 있습니다.

let fullName = "First Last"

let components = fullName.split{ !$0.isLetter }
print(components)  // "["First", "Last"]\n"

에, WMios 의 「」를 사용할 .componentsSeparatedByCharactersInSet구분 기호(공백, 쉼표 등)가 더 많은 경우 편리합니다.

특정 입력 내용:

let separators = NSCharacterSet(charactersInString: " ")
var fullName: String = "First Last";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["First", "Last"]

여러 구분 기호 사용:

let separators = NSCharacterSet(charactersInString: " ,")
var fullName: String = "Last, First Middle";
var words = fullName.componentsSeparatedByCharactersInSet(separators)

// words contains ["Last", "First", "Middle"]

스위프트 4

let words = "these words will be elements in an array".components(separatedBy: " ")

공백 문제

일반적으로 사람들은 이 문제와 나쁜 해결책을 계속해서 재발명합니다.이거 공간이에요?" " 및 "\n", "\t" 또는 지금까지 본 적이 없는 유니코드 공백 문자는 보이지 않기 때문에 작은 부분이 아닙니다.당신이 빠져나갈 수 있는 동안

약한 솔루션

import Foundation
let pieces = "Mary had little lamb".componentsSeparatedByString(" ")

리얼리티에 대한 이해가 필요한 경우는, 문자열이나 날짜의 WWDC 비디오를 봐 주세요.간단히 말해서, 애플이 이런 종류의 일상적인 일을 해결하도록 하는 것이 거의 항상 더 낫다.

견고한 솔루션:NSCaracter 사용세트

은 IMHO를 사용하는 입니다.NSCharacterSet앞서 말한 바와 같이 공백이 예상과 다를 수 있으며 애플은 공백 문자 집합을 제공했습니다.제공되는 다양한 문자 집합을 탐색하려면 Apple의 NSCaracterSet 개발자 설명서를 확인한 다음, 사용자의 요구에 맞지 않는 경우에만 새 문자 집합을 추가 또는 구성합니다.

NSCaracter 공백 설정

유니코드 일반 범주 Zs 및 CARTER TABULATION(U+0009)의 문자를 포함하는 문자 집합을 반환합니다.

let longerString: String = "This is a test of the character set splitting system"
let components = longerString.components(separatedBy: .whitespaces)
print(components)

Swift 4.2 및 Xcode 10의 경우

//This is your str
let str = "This is my String" //Here replace with your string

옵션 1

let items = str.components(separatedBy: " ")//Here replase space with your value and the result is Array.
//Direct single line of code
//let items = "This is my String".components(separatedBy: " ")
let str1 = items[0]
let str2 = items[1]
let str3 = items[2]
let str4 = items[3]
//OutPut
print(items.count)
print(str1)
print(str2)
print(str3)
print(str4)
print(items.first!)
print(items.last!)

옵션 2

let items = str.split(separator: " ")
let str1 = String(items.first!)
let str2 = String(items.last!)
//Output
print(items.count)
print(items)
print(str1)
print(str2)

옵션 3

let arr = str.split {$0 == " "}
print(arr)

옵션 4

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Apple 문서별...

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(separator: " "))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

print(line.split(separator: " ", maxSplits: 1))//This can split your string into 2 parts
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

print(line.split(separator: " ", maxSplits: 2))//This can split your string into 3 parts

print(line.split(separator: " ", omittingEmptySubsequences: false))//array contains empty strings where spaces were repeated.
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

print(line.split(separator: " ", omittingEmptySubsequences: true))//array not contains empty strings where spaces were repeated.
print(line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: false))
print(line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true))

split정답입니다.다음은 2개 이상의 공간에 대한 차이입니다.

스위프트 5

var temp = "Hello world     ni hao"
let arr  = temp.components(separatedBy: .whitespacesAndNewlines)
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr2 = temp.components(separatedBy: " ")
// ["Hello", "world", "", "", "", "", "ni", "hao"]
let arr3 = temp.split(whereSeparator: {$0 == " "})
// ["Hello", "world", "ni", "hao"]

Swift 4를 사용하면 문자 분할이 훨씬 쉬워지고 Strings에 새로운 분할 기능을 사용할 수 있습니다.

:: let s = "hi, hello" let a = s.split(separator: ",") print(a)

이제 'hi'와 'hello'가 붙은 배열이 있습니다.

스위프트 3

let line = "AAA    BBB\t CCC"
let fields = line.components(separatedBy: .whitespaces).filter {!$0.isEmpty}
  • 의 스트링 3을 반환합니다.AAA,BBB ★★★★★★★★★★★★★★★★★」CCC
  • 빈 필드를 필터링합니다.
  • 여러 공백 및 표 문자 처리
  • 행을 는, 「신규 행」을 합니다..whitespaces.whitespacesAndNewlines

Swift 4, Xcode 10 및 iOS 12 Update는 100% 기능

let fullName = "First Last"    
let fullNameArr = fullName.components(separatedBy: " ")
let firstName = fullNameArr[0] //First
let lastName = fullNameArr[1] //Last

상세한 것에 대하여는, 여기를 참조해 주세요.

Xcode 8.0 / Swift 3

let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")

var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last

먼 길:

var fullName: String = "First Last"
fullName += " " // this will help to see the last word

var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array

for Character in fullName.characters {
    if Character == " " {
        fullNameArr.append(newElement)
        newElement = ""
    } else {
        newElement += "\(Character)"
    }
}


var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last

이러한 답변의 대부분은 입력에 공백이 아닌 공백이 포함되어 있다고 가정합니다.만약 당신이 그 가정을 안전하게 할 수 있다면, (베넷에서) 받아들여지는 답변은 꽤 우아하고, 그리고 가능한 한 제가 할 수 있는 방법을 택할 것입니다.

이러한 가정을 할 수 없는 경우, 보다 견고한 솔루션은 대부분의 답변이 고려하지 않은 다음과 같은 조건을 충족해야 합니다.

  • 탭/새 행/스페이스(공백), 반복 문자 포함
  • 선두/후진 공백
  • (Apple/Linux)\n Windows(\r\n

이러한 경우에 대처하기 위해 이 솔루션은 regex를 사용하여 모든 공백(반복 및 Windows 줄바꿈 문자 포함)을 단일 공백으로 변환하고 잘라낸 다음 단일 공백으로 분할합니다.

스위프트 3:

let searchInput = "  First \r\n \n \t\t\tMiddle    Last "
let searchTerms = searchInput 
    .replacingOccurrences(
        of: "\\s+",
        with: " ",
        options: .regularExpression
    )
    .trimmingCharacters(in: .whitespaces)
    .components(separatedBy: " ")

// searchTerms == ["First", "Middle", "Last"]

분할할 문자열에 여러 개의 제어 문자가 있을 수 있는 시나리오가 있었습니다.저는 이 부분을 애플이 처리하도록 내버려두었습니다.

다음은 iOS 10의 Swift 3.0.1에서 작동합니다.

let myArray = myString.components(separatedBy: .controlCharacters)

흥미로운 사례를 하나 찾았어요

방법 1

var data:[String] = split( featureData ) { $0 == "\u{003B}" }

이 명령어를 사용하여 서버에서 로드된 데이터에서 일부 기호를 분할하면 시뮬레이터에서 테스트하고 테스트 장치와 동기화하는 동안 분할될 수 있지만 게시 앱 및 애드혹에서 분할되지 않습니다.

이 오류를 추적하는 데 시간이 많이 걸립니다. Swift Version이나 iOS Version 또는 둘 다에서 욕을 했을 수 있습니다.

HTML 코드에 관한 것도 아닙니다.StringByRemovingPercentEncoding을 시도해도 동작하지 않기 때문입니다.

2015년 10월 10일 추가

Swift 2.0에서는 이 방법이 로 변경되었습니다.

var data:[String] = featureData.split {$0 == "\u{003B}"}

방법 2

var data:[String] = featureData.componentsSeparatedByString("\u{003B}")

이 명령어를 사용하면 서버에서 로드되는 동일한 데이터를 올바르게 분할할 수 있습니다.


결론적으로, 저는 방법 2를 사용하는 것을 추천합니다.

string.componentsSeparatedByString("")

Swift 4에서 문자열을 배열로 분할하는 단계입니다.

  1. 문자열을 할당하다
  2. @ spliting을 기반으로 합니다.

주의: variableName.components (separatedBy: "split 키워드")

let fullName: String = "First Last @ triggerd event of the session by session storage @ it can be divided by the event of the trigger."
let fullNameArr = fullName.components(separatedBy: "@")
print("split", fullNameArr)

이렇게 하면 분할 부품 배열이 직접 제공됩니다.

var fullNameArr = fullName.components(separatedBy:" ")

이렇게 쓸 수 있어요.

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

또는 Swift 2에서는 다음과 같은 작업을 수행할 수 있습니다.

let fullName = "First Last"
let fullNameArr = fullName.characters.split(" ")
let firstName = String(fullNameArr[0])

스위프트 4

let string = "loremipsum.dolorsant.amet:"

let result = string.components(separatedBy: ".")

print(result[0])
print(result[1])
print(result[2])
print("total: \(result.count)")

산출량

loremipsum
dolorsant
amet:
total: 3

가장 간단한 해결책은

let fullName = "First Last"

let components = fullName.components(separatedBy: .whitespacesAndNewlines).compactMap { $0.isEmpty ? nil : $0 }

다른 등)에 이 경우, 「」( 「」, 「」, 「」, 「」)는 할 수 있습니다.「」2」는 변경할 수 .CharacterSet원하는 문자를 더 많이 포함하려면 정규 표현 디코더를 사용하면 됩니다. 이렇게 하면 문자열을 디코딩하는 데 사용할 수 있는 정규 표현을 디코딩 프로토콜을 구현하는 클래스/구조에 직접 쓸 수 있습니다.이런 건 오버킬이지만 좀 더 복잡한 문자열의 예시로 사용한다면 더 말이 될 수도 있습니다.

예를 들어 "Hello World"라는 이름의 변수가 있으며 이를 분할하여 두 개의 다른 변수로 저장하는 경우 다음과 같이 사용할 수 있습니다.

var fullText = "Hello World"
let firstWord = fullText.text?.components(separatedBy: " ").first
let lastWord = fullText.text?.components(separatedBy: " ").last

이것은 베타 5에서 다시 변경되었습니다.으악! 이제 수집 방법이야유형

구식:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}

신규:

var fullName = "First Last"
var fullNameArr = fullName.split {$0 == " "}

Apple 릴리즈 노트

문자열 처리는 Swift에서 여전히 어려운 과제이며, 다른 답변에서도 알 수 있듯이, 계속해서 크게 변화하고 있습니다.상황이 안정되고 좀 더 단순해졌으면 좋겠다.이것은 여러 개의 구분 문자를 사용하여 현재 3.0 버전의 Swift를 사용하는 방법입니다.

스위프트 3:

let chars = CharacterSet(charactersIn: ".,; -")
let split = phrase.components(separatedBy: chars)

// Or if the enums do what you want, these are preferred. 
let chars2 = CharacterSet.alphaNumerics // .whitespaces, .punctuation, .capitalizedLetters etc
let split2 = phrase.components(separatedBy: chars2)

나는 PHP와 같은 loosy split을 찾고 있었다.explode빈 시퀀스가 결과 배열에 포함되는 경우 다음과 같이 처리했습니다.

"First ".split(separator: " ", maxSplits: 1, omittingEmptySubsequences: false)

출력:

["First", ""]
let str = "one two"
let strSplit = str.characters.split(" ").map(String.init) // returns ["one", "two"]

Xcode 7.2 (7C68)

스위프트 2.2 오류 처리 & capitalized String 추가됨:

func setFullName(fullName: String) {
    var fullNameComponents = fullName.componentsSeparatedByString(" ")

    self.fname = fullNameComponents.count > 0 ? fullNameComponents[0]: ""
    self.sname = fullNameComponents.count > 1 ? fullNameComponents[1]: ""

    self.fname = self.fname!.capitalizedString
    self.sname = self.sname!.capitalizedString
}

오프톱:

서브스트링(문자가 아닌)을 사용하여 문자열을 분할하는 방법을 찾는 사용자를 위해 다음과 같은 솔루션이 있습니다.

// TESTING
let str1 = "Hello user! What user's details? Here user rounded with space."
let a = str1.split(withSubstring: "user") // <-------------- HERE IS A SPLIT
print(a) // ["Hello ", "! What ", "\'s details? Here ", " rounded with space."]

// testing the result
var result = ""
for item in a {
    if !result.isEmpty {
        result += "user"
    }
    result += item
}
print(str1) // "Hello user! What user's details? Here user rounded with space."
print(result) // "Hello user! What user's details? Here user rounded with space."
print(result == str1) // true

/// Extension providing `split` and `substring` methods.
extension String {
    
    /// Split given string with substring into array
    /// - Parameters:
    ///   - string: the string
    ///   - substring: the substring to search
    /// - Returns: array of components
    func split(withSubstring substring: String) -> [String] {
        var a = [String]()
        var str = self
        while let range = str.range(of: substring) {
            let i = str.distance(from: str.startIndex, to: range.lowerBound)
            let j = str.distance(from: str.startIndex, to: range.upperBound)
            let left = str.substring(index: 0, length: i)
            let right = str.substring(index: j, length: str.length - j)
            a.append(left)
            str = right
        }
        if !str.isEmpty {
            a.append(str)
        }
        return a
    }
    
    /// the length of the string
    public var length: Int {
        return self.count
    }
    
    /// Get substring, e.g. "ABCDE".substring(index: 2, length: 3) -> "CDE"
    ///
    /// - parameter index:  the start index
    /// - parameter length: the length of the substring
    ///
    /// - returns: the substring
    public func substring(index: Int, length: Int) -> String {
        if self.length <= index {
            return ""
        }
        let leftIndex = self.index(self.startIndex, offsetBy: index)
        if self.length <= index + length {
            return String(self[leftIndex..<self.endIndex])
        }
        let rightIndex = self.index(self.endIndex, offsetBy: -(self.length - index - length))
        return String(self[leftIndex..<rightIndex])
    }

}

언급URL : https://stackoverflow.com/questions/25678373/split-a-string-into-an-array-in-swift

반응형