How to get the first characters in a string? (Swift 3)
16,787
Solution 1
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>
Solution 2
let name = "Ajay"
// Use following line to extract first chracter(In String format)
print(name.characters.first?.description ?? "");
// Output : "A"
Solution 3
The correct way would be to use indexes as following:
let string = "123 456"
let firstCharIndex = string.index(string.startIndex, offsetBy: 1)
let firstChar = string.substring(to: firstCharIndex)
print(firstChar)
Solution 4
This Code provides you the first character of the string. Swift provides this method which returns character? you have to wrap it before use
let str = "FirstCharacter" print(str.first!)
Solution 5
Similar to OOPer's:
let string = "<ONLINE>"
let closingTag = CharacterSet(charactersIn: ">")
if let closingTagIndex = string.rangeOfCharacter(from: closingTag) {
let mySubstring = string.substring(with: string.startIndex..<closingTagIndex.upperBound)
}
Or with regex:
let string = "<ONLINE>jhkjhkh>"
if let range = string.range(of: "<[A-Z]+>", options: .regularExpression) {
let mySubstring = string.substring(with: range)
}
Author by
Freddy Benson
Updated on June 04, 2022Comments
-
Freddy Benson almost 2 years
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 usingstartIndex
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
?