Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

ios - Question on how to split a string into an array of desired strings in Swift

I have a question.

There are several ways to divide a string into a string array.

First of all, the way I made a string into a string array is,

let str = "F'2R'UU2"
let strArr: [String] = str.map { String($0) }
//strArr => ["F", "'", "2", "R", "'", "U", "U", "2"]

It turns into a string array like this

But I would like to divide based on the uppercase alphabet. For example, if you divide the string F2, it becomes ["F2"] instead of ["F", "2"], and if you divide the string F'2, it becomes ["F", "'", "2"] instead of ["F'2"]

The result I want is,

let str = "F'2R'UU2"
<<<str to strArr>>>
//strArr => ["F'2", "R'", "U", "U2"]

Please let me know!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use reduce to iterate the string over each character and either append it to an array if it is an uppercase letter or add it to the last element of the array otherwise

let str = "F'2R'UU2"

let res = str.reduce(into: [String]()) {
    if $1.isUppercase || $0.isEmpty {
        $0.append("($1)") 
    } else {
        $0[$0.count - 1] = $0.last! + "($1)"
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...