Freddy Benson Freddy Benson - 1 month ago 12
Swift Question

How to get the first characters in a string? (Swift 3)

I want to get a substring out of a string which starts with either

"<ONLINE>"
or
"<OFFLINE>"
(which should become my substring). When I try to create a Range object, I can easily access the the first character by using
startIndex
but how do I get the index of the closing bracket of my substring which will be either the 8th or 9th character of the full string?

UPDATE:

A simple example:

let onlineString:String = "<ONLINE> Message with online tag!"

let substring:String = // Get the "<ONLINE> " part from my string?

let onlineStringWithoutTag:String = onlineString.replaceOccurances(of: substring, with: "")

// What I should get as the result: "Message with online tag!"


So basically, the question is: what do I do for
substring
?

Answer

If you did not want to use range

let onlineString:String = "<ONLINE> Message with online tag!"

let substring:String = onlineString.components(separatedBy: " ")[0]

print(substring) // <ONLINE>