cakes88
cakes88

Reputation: 1917

Grab a Specific Line in a String - Swift

New to swift/xcode/ios -- I want to grab the specific line from a string but not sure how to go about it. Here is my string:

PRICE                             9.00
TAX                               3.54
TOTAL                             12.54

CASH                              12.54

        THANK YOU FOR SHOPPING!
Receipt Code: 1HI 12D0 00A 0024 //want to grab this 14 character code

Does anyone have an effective way to scan the string then grab that 14 character code? It will sometimes be up a few lines or below a few lines but always following 'Receipt Code: xxx xxxx xxx xxxx' I essentially just want it to return the coe without spaces.

Upvotes: 0

Views: 269

Answers (3)

kientux
kientux

Reputation: 1792

If "Receipt Code" appears only once and the code is the last line:

let bill = self.giveMyTheBill()
let range = bill.rangeOfString("Receipt Code:")
if range != nil {
    let code = bill.substringFromIndex(range!.endIndex)
                   .stringByReplacingOccurrencesOfString(" ", withString: "")
}

Upvotes: 1

vadian
vadian

Reputation: 285082

A solution with regular expression.

However it assumes that the character groups are 3 - 4 - 3 - 4

let string = "PRICE                             9.00\nTAX                               3.54\nTOTAL                             12.54\n\nCASH                              12.54\n\nTHANK YOU FOR SHOPPING!\nReceipt Code: 1HI 12D0 00A 0024 //want to grab this 14 character code"

let pattern = "\\w{3}[ ]\\w{4}[ ]\\w{3}[ ]\\w{4}"
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
  if let result = regex.firstMatchInString(string, options: NSMatchingOptions(), range: NSMakeRange(0, string.characters.count)) {
    let code = (string as NSString).substringWithRange(result.range).stringByReplacingOccurrencesOfString(" ", withString: "")
  }
} catch let error as NSError {
  print(error)
}

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236360

let inputString = "PRICE                             9.00\nTAX                               3.54\nTOTAL                             12.54\n\nCASH                              12.54\n\nTHANK YOU FOR SHOPPING!\nReceipt Code: 1HI 12D0 00A 0024" //want to grab this 14 character code"
let searchString = "Receipt Code: "

if let firstFound = inputString.rangeOfString(searchString)?.first {
    let code = inputString.substringWithRange(firstFound.advancedBy(searchString.characters.count)..<firstFound.advancedBy(searchString.characters.count+17))
        .stringByReplacingOccurrencesOfString(" ", withString: "")   // "1HI12D000A0024"
}

Upvotes: 1

Related Questions