带有substringWithRange

时间:2015-09-05 12:50:10

标签: ios string swift2

我想从String中获取第一个char。它应该很容易但我无法在Swift 2.0中使用(使用Xcode beta 6)。

Get nth character of a string in Swift programming language

我也尝试过这种方法。它使用扩展但我无法使用该方法检索。我可以知道该怎么做吗?

7 个答案:

答案 0 :(得分:7)

两种解决方案,无需转换为NSString

let string = "Hello"
let firstChar1 = string.substringToIndex(string.startIndex.successor())

let firstChar2 = string.characters.first

Swift 2的更新:

由于Swift 2返回Character而不是String,因此必须创建新的String

let firstChar2 = String(string.characters.first!)

Swift 3的更新:

successor()已替换为index(after:..)

let firstChar1 = string.substring(to:string.index(after: string.startIndex))

答案 1 :(得分:4)

试试这个,

let str = "hogehoge"
let text = (str as NSString).substringFromIndex(1) // "ogehoge"

答案 2 :(得分:4)

对于它的价值(以及搜索和查找此主题的人),不将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。

答案 3 :(得分:2)

试试这个

let myString = "My String" as NSString
myString.substringWithRange(NSRange(location: 0, length: 3))

答案 4 :(得分:2)

在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)]

答案 5 :(得分:0)

var mySuperCoolString = "Hello, World!!!!!!!!1!!";    
println(mySuperCoolString.substringWithRange(Range<String.Index>(start: advance(mySuperCoolString.startIndex, 0), end: advance(mySuperCoolString.startIndex, 1))));

这应打印出H

答案 6 :(得分:-1)

Swift 2.2和Swift 3.0

let string = "12134"
string.substringWithRange(string.startIndex..<string.startIndex.advancedBy(2))