如何在swift4中获取子字符串并使用最简单的方法?

如何在swift4中获取子字符串并使用最简单的方法?

问题描述:

我遇到了问题swift String,任何人都可以帮助我吗?如何在swift4中获取子字符串并使用最简单的方法?

我知道我可以使用String.Index得到一个子

let country = "德国 Germany" 
let flag3 = country[country.index(country.startIndex, offsetBy: 1)..<country.index(country.startIndex, offsetBy: 3)] 
print(flag3) //德国 

,但我觉得它(Range<String.Index>)是非常乏味的。我怎样才能得到字符串的确切范围像NSString API:

NSString *ns_country = @"德国 Germany"; 
NSString *sub = [ns_country substringWithRange:NSMakeRange(0, 2)];//德国 
+0

希望这可以帮助你https://*.com/questions/45562662/how-can-i-use-string-slicing-subscripts-in-swift-4 –

+0

其实,它是一个子字符串类型。我只想知道它是否有创建'Range '的优雅方法。 – hupengfei

let ns_country = "德国 Germany" 
let range = ns_country.index(of: "国")! 
let newStr = ns_country[...range] 

其实这里中newstr是substring如果你想String

let newStr = String(ns_country[...endOfSentence]) 

你可以阅读更多有关新子here

+0

谢谢,但有时候这不是一个好主意,如果我在字符串的不同范围内有很多“国”,我只想得到一个特别的。 – hupengfei