Swift: substring (integer/number) from a string

swift 5 string(substring)
swift string to int
swift truncate string
swift 5 substring
swift string character at index
get number from string swift
swift 4 string substring
swift string split

I'm working on a Speech Recogniser module in my app. Speech recognizer returns a string (maybe some time with garbage string information, closely matching with user's speech) and I have to evaluate specific command from a string.

Here are some speech result string examples, that I'm getting:

  • "open case"
  • "open case 1234"
  • "open case id 3421"
  • "open case no 9546"
  • "open case number 5241"
  • "open case 9552 open case"
  • "open case open case 6842"
  • "open case bla bla 5415 bla"
  • "open case 1234 bla bla"
  • "open case number 54675 bla bla 1234 bla" . // first integer should be considered in command

Now, I've a set of command list, one of command is open case <Integer value>

I could easily evaluate the word open case using substring utility functions of Swift. But the problem is, I've to find out (identify and get) an integer number from a speech string after keyword open case.

I've looked around the following answer but couldn't find the exact result/solution:

  • Substring Integers from String
  • Swift : How to get the string before a certain character?
  • Swift: How to get everything after a certain set of characters

Swift How to get integer from string and convert it into integer, First, we split the string so we can process the single items. Then we use NSCharacterSet to select the numbers only. import Foundation let str = "I have to buy 3  Swift has a dedicated Substring type (String.SubSequence) that is designed to hold slices of strings, which is a performance optimization: when you store part of a string in a different variable, Swift can simply point the substring at the parent string rather than copy all the data.

You can use something like:

let string = "open case 9552 open case"

if let number = string.components(separatedBy: .whitespaces).compactMap(Int.init).first {
    print(number)
}

If you're using Swift 4.0 or below use flatMap instead of compactMap.

Substring, This example defines a rawData string with some unstructured data, and then uses the string's prefix(while:) method to create a substring of the numeric prefix:. A substring holds a reference to the entire storage of the string it comes from, not just to the portion it presents, even when there is no other reference to the original string. Storing substrings may, therefore, prolong the lifetime of string data that is no longer otherwise accessible, which can appear to be memory leakage.

I like regex.

let input = "open case 1234 bla bla"
let pattern = "open case ([0-9]+)"
do {
    let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
    if matches.count > 0 {
        let match = matches[0]
        let r = match.range(at: 1)
        let num = input.substring(with: Range(r, in: input)!)
        // "1234"
    }
} catch {
    print("illegal regex")
}

How Strings and Substrings work in Swift - Suragch, As of Swift 4, when you get some substring from a String, you get a Substring type back rather than a String. You can get a substring from a string by using subscripts or a number of other Index and not an Int index for the range, though​. - Get substring from range - Get the length of a string - Loop through characters in string - Repeat a string X times - Replace string in string - Reverse a string - Split a string by another string - Trim whitespace from a string - Use string interpolation

How to convert a String to an Int, Because strings might contain something that isn't a number – e.g. “Fish” rather than “556” – the Int initializer will return an optional integer, so if  Result: The substring is returned by indexing the string with the range. It equals "two.". Swift program that gets substring // This is the input string. let s = "one two three" // Get range 4 places from the start, and 6 from the end. let r = s. index (s.startIndex, offsetBy: 4)..<s.

Swift Substring Examples, Start: We call index() on the string and pass startIndex and an offsetBy int to get the start of the range. We advance 4 chars. Result: We skip past the first 4  If you have an integer hiding inside a string, you can convert between the two just by using the integer's initializer, like this: let myString1 = "556" let myInt1 = Int(myString1) Because strings might contain something that isn’t a number – e.g. “Fish” rather than “556” – the Int initializer will return an optional integer, so

How to make `String.Index` with `Int` offset (distance , String has O(1) substring extraction using String. Also I treat returned offset number as an opaque type (though it's actually just Int ), and  Inside a Substring. Part of the magic of substrings is that they reuse the storage of their “parent” string. You can think of a substring as a base string and a range. That means a 100-character slice of an 8000-character string doesn’t need to allocate and duplicate storage for those 100 characters.

Comments
  • What about a regex pattern "open case [0-9]+"?
  • Need you help one more time to find out a accurate regex pattern, matching with this string open bla case bla 62 72 769 bla bla. I've tried this one open\\D+case\\D+(\\d+)\\s*(\\d+)\\s*(\\d+) but it fails if there are more than 3 matches for combination of space + number.
  • Try "open\\D+case\\D+([\\d ]+\\d)", the numeric search considers digits and spaces with a trailing digit.
  • Thank you.. You are great! Why couldn't I thought it?
  • If you also want to consider only a single digit you have to replace the + after the closing bracket (one or more) with * (zero or more)
  • I'm showing you a possible technique, not writing your code for you.