How do you extract numbers from a string that is composed of random alphanumeric characters? I used the string’s view of the characters as a collection of Unicode scalar values to achieve this task. Each character in a string has a Unicode scalar value that you can grab from the string’s unicodeScalars property. Let’s look at the following example:
For the example above, we looped through each of the characters in the alphaNumericString variable and printed out the corresponding Unicode scalar value. Each of the value is a unique representation of the character.
So for the digits, you can identify all the corresponding Unicode scalar values as follows:
Note that digit is a Unicode.scalar type and from there you can access the Unicode value by accessing the valueproperty as shown in the example above.
The Unicode scalar value is a UTF-32 bit representation. So you can create your own Unicode scalar instance given a value in UTF-32 bit representation like below.
So what’s happening here? The first part creates two variables by explicitly specifying the type and assigning the string of 0 and 9. The second part uses the Unicode scalar value to create the numbers from 0 to 9.
Since you have the range of Unicode scalar values that correspond to some digits, you can identify whether the character is a digit or something else:
The final step is to use the number in the string, so let’s extract the digits and convert it into something more usable:
So as we are going through the Unicode scalar in the string, you are checking if the value matches any digits in the range from 48 to 57. You grab each of the digits and store it into a variable and break out of the loop as soon as you find a non-numeric letter.
If you want to have some fun, you can also attempt this leetcode problem using what you have learned. Post your solutions below and we can compare our solutions.