swift - 在字符串中,如何获取第一个字符 ( Swift 3 )?

我想从字符串中获取一个字符串,该字符串以 "<ONLINE>" 或者 "<OFFLINE>" ( 它应该成为我的子字符串) 开头。 当我尝试创建一个Range对象时,我可以通过使用startIndex轻松访问第一个字符但是如何获得我的子字符串的结束括号的索引,它将是完整字符串的第8个或第9个字符?

更新:

一个简单的例子:


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!"



所以问题是: 我该为 substring 做什么?

时间:

如果你不想使用范围


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



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



print(substring)//<ONLINE>




let name ="Ajay"



//Use following line to extract first chracter(In String format)



print(name.characters.first?.description??"");



//Output :"A"



正确的方法是使用索引如下:


let string ="123 456"


let firstCharIndex = string.index(string.startIndex, offsetBy: 1)


let firstChar = string.substring(to: firstCharIndex)


print(firstChar)



与OOPer 的相似:


let string ="<ONLINE>"



let closingTag = CharacterSet(charactersIn:">")


if let closingTagIndex = string.rangeOfCharacter(from: closingTag) {


 let mySubstring = string.substring(with: string.startIndex..<closingTagIndex.upperBound)


}



或者使用 正规表达式:


let string ="<ONLINE>jhkjhkh>"



if let range = string.range(of:"<[A-Z]+>", options:. regularExpression) {


 let mySubstring = string.substring(with: range)


}



这里代码对你的目的有帮助:


let myString ="<ONLINE>abc"


if let rangeOfClosingAngleBracket = myString.range(of:">") {


 let substring = myString.substring(to: rangeOfClosingAngleBracket.upperBound)


 print(substring)//-><ONLINE>


}



...