是时候承认失败了……

在Objective-C中,我可以使用如下内容:

NSString* str = @"abcdefghi";
[str rangeOfString:@"c"].location; // 2

在Swift中,我看到了类似的东西:

var str = "abcdefghi"
str.rangeOfString("c").startIndex

...但这只是给了我一个字符串。索引,我可以使用它下标回原始字符串,但不能从中提取位置。

FWIW,字符串。Index有一个名为_position的私有ivar,其中有正确的值。我只是不明白怎么会暴露出来。

我知道我自己可以很容易地将其添加到String中。我更好奇在这个新的API中我缺少了什么。


当前回答

Swift 3.0让这个更加冗长:

let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.index(of: needle) {
    let pos = string.characters.distance(from: string.startIndex, to: idx)
    print("Found \(needle) at position \(pos)")
}
else {
    print("Not found")
}

扩展:

extension String {
    public func index(of char: Character) -> Int? {
        if let idx = characters.index(of: char) {
            return characters.distance(from: startIndex, to: idx)
        }
        return nil
    }
}

在Swift 2.0中,这变得更加容易:

let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.indexOf(needle) {
    let pos = string.startIndex.distanceTo(idx)
    print("Found \(needle) at position \(pos)")
}
else {
    print("Not found")
}

扩展:

extension String {
    public func indexOfCharacter(char: Character) -> Int? {
        if let idx = self.characters.indexOf(char) {
            return self.startIndex.distanceTo(idx)
        }
        return nil
    }
}

斯威夫特1。x实现:

对于纯Swift解决方案,可以使用:

let string = "Hello.World"
let needle: Character = "."
if let idx = find(string, needle) {
    let pos = distance(string.startIndex, idx)
    println("Found \(needle) at position \(pos)")
}
else {
    println("Not found")
}

作为String的扩展:

extension String {
    public func indexOfCharacter(char: Character) -> Int? {
        if let idx = find(self, char) {
            return distance(self.startIndex, idx)
        }
        return nil
    }
}

其他回答

String是NSString的桥接类型,add

import Cocoa

到你的swift文件,并使用所有“旧”的方法。

如果你想知道一个字符作为int值在字符串中的位置,使用这个:

let loc = newString.range(of: ".").location

如果你只需要一个字符的索引,最简单,快速的解决方案(正如Pascal已经指出的那样)是:

let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)

在我看来,了解逻辑本身的更好方法是下面

 let testStr: String = "I love my family if you Love us to tell us I'm with you"
 var newStr = ""
 let char:Character = "i"

 for value in testStr {
      if value == char {
         newStr = newStr + String(value)
   }

}
print(newStr.count)

在Swift 2.0中,下面的函数在给定字符之前返回一个子字符串。

func substring(before sub: String) -> String {
    if let range = self.rangeOfString(sub),
        let index: Int = self.startIndex.distanceTo(range.startIndex) {
        return sub_range(0, index)
    }
    return ""
}