[英]How to use substringWithRange() with a startIndex and a length in Swift
[英]Swift 2.0 String with substringWithRange
我想从String中获取第一个char。 它应该很容易,但我不能在Swift 2.0中使用(使用Xcode beta 6)。
我也试过那种方法。 它使用扩展但我无法使用该方法检索。 我可以知道该怎么办吗?
没有强制转换为NSString的两种解决方案
let string = "Hello"
let firstChar1 = string.substringToIndex(string.startIndex.successor())
let firstChar2 = string.characters.first
Swift 2更新:
由于斯威夫特2返回Character
,而不是String
新的String
必须创建。
let firstChar2 = String(string.characters.first!)
Swift 3更新:
successor()
已被index(after:..)
替换index(after:..)
let firstChar1 = string.substring(to:string.index(after: string.startIndex))
试试这个,
let str = "hogehoge"
let text = (str as NSString).substringFromIndex(1) // "ogehoge"
对于它的价值(以及搜索和查找此主题的人),不将String转换为NSString,您需要使用Swift 2.1执行以下操作:
let myString = "Example String"
let mySubString = myString.substringWithRange(Range<String.Index>(start: myString.startIndex.advanceBy(0), end: myString.startIndex.advanceBy(4)))
print(mySubString) //'Exam'
这将打印出“考试”。 必须说它比Obj-C更冗长。 那是在说些什么...... ;-)但它完成了工作而没有投射到NSString。
试试这个
let myString = "My String" as NSString
myString.substringWithRange(NSRange(location: 0, length: 3))
在Swift 2中, String
不是任何东西的集合。 根据文件:
/// `String` is not itself a collection of anything. Instead, it has
/// properties that present the string's contents as meaningful
/// collections:
///
/// - `characters`: a collection of `Character` ([extended grapheme
/// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster))
/// elements, a unit of text that is meaningful to most humans.
///
/// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode
/// scalar
/// values](http://www.unicode.org/glossary/#unicode_scalar_value))
/// the 21-bit codes that are the basic unit of Unicode. These
/// values are equivalent to UTF-32 code units.
///
/// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit
/// elements of the string's UTF-16 encoding.
///
/// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit
/// elements of the string's UTF-8 encoding.
假设你想找到第二个字符,
var str = "Hello, playground"
let chars = str.characters
let n = 2
let c = str.characters[str.characters.startIndex.advancedBy(n)]
var mySuperCoolString = "Hello, World!!!!!!!!1!!";
println(mySuperCoolString.substringWithRange(Range<String.Index>(start: advance(mySuperCoolString.startIndex, 0), end: advance(mySuperCoolString.startIndex, 1))));
这应该打印出H
Swift 2.2和Swift 3.0
let string = "12134"
string.substringWithRange(string.startIndex..<string.startIndex.advancedBy(2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.