0

How can I break down a string by spaces? I’m used to taking data before/after a word or special character or a space. However I’m working on a decoder app where my string would look like:

This is a downloaded code that would be set to a string: “09627189762”

let str = downloadedCode
print(str) //09627189762

And I need it to format it here so that it can print as seen below:

let strA = //breakdown first 2 characters
let strB = //breakdown 3rd character etc
let strC = //do something
let strD = //do something
let strE = //do something
let strF = //do something

print(strA) //prints 09
print(strB) //prints 6
print(strC) //prints 27
print(strD) //prints 189
print(strE) //prints 7
print(strF) //prints 62

These numbers all have a different meaning that need coding, so I have to break the string down based on characters count ?

  • 1
    You should give ***a lot*** more detail on what you're asking. I don't see any particular pattern associating that input and output – Alexander Apr 19 '20 at 01:08
  • 1
    Based on the question I am not sure if this is what you need but you probably are wanting to break this down into substrings based on your own knowledge of how they should be broken up. Check out this SO post https://stackoverflow.com/questions/39677330/how-does-string-substring-work-in-swift – Grant Singleton Apr 19 '20 at 01:29
  • Thanks gwsingleton. That will work, it will let me access each part. –  Apr 19 '20 at 07:45
  • And Alexander, sorry if my question is not written the best. I’m new here, I don’t see what details are missing. Let me update it slightly to see if that helps you –  Apr 19 '20 at 07:47

1 Answers1

0

You can use a regular expression to split your input string into constant-length parts. In the example below, each (\\d{X}) part of the pattern means "match a sequence of X digits".

func splitString(_ str: String) -> [String] {
    let regex = try! NSRegularExpression(pattern: 
       "(\\d{2})(\\d{1})(\\d{2})(\\d{3})(\\d{1})(\\d{2})")
    var parts = [String]()
    if let match = regex.firstMatch(in: str, range: NSMakeRange(0, str.count)) {
        let nsstr = str as NSString
        for i in 1 ..< match.numberOfRanges {
            let part = nsstr.substring(with: match.range(at: i))
            parts.append(part)
        }
    }
    return parts
}

print(splitString("09627189762")) // ["09", "6", "27", "189", "7", "62"]

Gereon
  • 17,258
  • 4
  • 42
  • 73