Easy access for SubStrings in Swift 4.x
Swift is fun and easy, however there are portions that are too complicated and they make using Swift an extra effort. Pointers are cumbersome and painful but they are the only way to manage data in C. In Swift you do not have to bother about pointers but when you deal with Slices, StringIndex, etc simply getting a character from a string is difficult. This is not a long article but a short tip that shows how you can quickly create a sub-string without the complex ways of setting the
A Swift String is an array of characters and you can manage an array like an array, i.e. access elements using a numeric index. so, consider the code
Getting the first n characters can be sliced easily using the method prefix.
Similarly, the last 10 characters can be gotten using the suffix function as
However the problem is that when you want to slice a string for a substring, it gets a bit tricky, with code like
An alternative and in my opinion a more readable way to do that is, convert it to an array of characters and then create a string from a subset of the array range. Conversion of the string to array and back can be more CPU cycles than some other methods, but at least this is more readable and understandable than the code above.
startIndex
, endIndex
, etc.A Swift String is an array of characters and you can manage an array like an array, i.e. access elements using a numeric index. so, consider the code
var mystring = "This is a string that has quite a few characters"
Getting the first n characters can be sliced easily using the method prefix.
print(mystring.prefix(10))
would print the first 10 characters.Similarly, the last 10 characters can be gotten using the suffix function as
print(mystring.suffix(10))
.However the problem is that when you want to slice a string for a substring, it gets a bit tricky, with code like
let startpos = mystring.index(mystring.startIndex, offsetBy: 5, limitedBy: mystring.endIndex) ?? mystring.startIndex let endpos = mystring.index(mystring.startIndex, offsetBy: 20, limitedBy: mystring.endIndex) ?? mystring.endIndex let result = String(mystring[startpos..<endpos])
An alternative and in my opinion a more readable way to do that is, convert it to an array of characters and then create a string from a subset of the array range. Conversion of the string to array and back can be more CPU cycles than some other methods, but at least this is more readable and understandable than the code above.
let startPos = 5 let endPos = 20 let charArray = Array(mystring) let newResults = String(charArray[startPos..
That's all Folks... for now, a quick tip in working with swift. More later...
Comments
Post a Comment