sk123
sk123

Reputation: 600

How to split a string that doesn't have a separator in Swift

I'm looking to split this string in 4 parts. So far i'm only able to split it using components(separatedBy:) method. However i want i also to last word teamId4 into 2 parts where i can get teamId and 4 the number. All the solutions i have looked at always have separators in them like string having either spaces, lines, full stops etc which makes it quite easy. How can i achieve this output player23, 8, teamId, 4

var player = "player23_8_chelseaId4"

var splittedString: [String] {
    let stringArray = player.components(separatedBy: "_")
    let playerID = stringArray[0]
    let playerIndex = stringArray[1]
    let team = stringArray[2]
    // Would like "4" as the last string in the array
    let array = [playerID, playerIndex, team]
    return array
}

This is the output so far

["player23", "8", "chelseaId4"]

Desired output would be

["player23", "8", "chelseaId", "4"]

Upvotes: 0

Views: 115

Answers (3)

vadian
vadian

Reputation: 285069

This is the Regular Expression solution.

In the pattern the 4 pairs of parentheses represent the 4 captured strings, \\w+ means one or more word characters. The separators are the two underscore characters and the Id string in which the latter is captured, too.

func splittedString(from player : String) throws -> [String] {
    var result = [String]()
    let pattern = "^(\\w+)_(\\w+)_(\\w+Id)(\\w+)$"
    let regex = try NSRegularExpression(pattern: pattern)
    if let match = regex.firstMatch(in: player, range: NSRange(player.startIndex..., in: player)) {
        for i in 1..<match.numberOfRanges {
            result.append(String(player[Range(match.range(at: i), in: player)!]))
        }
    }
    return result
}

let player = "player23_8_chelseaId4"
let splitted = try splittedString(from: player) // ["player23", "8", "chelseaId", "4"]

If you want only chelsea without Id change the pattern to "^(\\w+)_(\\w+)_(\\w+)Id(\\w+)$"

Upvotes: 2

D. Wolf
D. Wolf

Reputation: 1

Is the "Id" string after every team name? So you could search for the substring Id and cut the string after it.

Upvotes: 0

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

var player = "player23_8_chelseaId4"

var splittedString: [String] {
    let stringArray = player.components(separatedBy: "_")
    let playerID = stringArray[0]
    let playerIndex = stringArray[1]
    let team = stringArray[2]

    let temp = team.components(separatedBy: "Id")
    // Would like "4" as the last string in the array
    let array = [playerID, playerIndex,"\(temp[0])Id" , temp[1]]
    return array
}

print(splittedString) // ["player23", "8", "chelseaId", "4"]

Upvotes: 1

Related Questions