是时候承认失败了……

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

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

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

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

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

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

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


当前回答

如果您正在寻找简单的方法来获得字符或字符串的索引,请检查这个库http://www.dollarswift.org/#indexof-char-character-int

您也可以使用另一个字符串或正则表达式模式从字符串中获取indexOf

其他回答

extension String{
    func contains(find: String)->Bool{
        return self.range(of: find) != nil
    }
}
 
func check(n:String, h:String)->Int{
    let n1 = n.lowercased()
    let h1 = h.lowercased()//lowercase to make string case insensitive
    var pos = 0 //postion of substring
    if h1.contains(n1){
       // checking if sub string exists
        if let idx = h1.firstIndex(of:n1.first!){
             let pos1 = h1.distance(from: h1.startIndex, to: idx)
           pos = pos1
        }
        return pos
    }
    else{
        return -1
    }
}
 
print(check(n:"@", h:"hithisispushker,he is 99 a good Boy"))//put substring in n: and string in h
    // Using Swift 4, the code below works.
    // The problem is that String.index is a struct. Use dot notation to grab the integer part of it that you want: ".encodedOffset"
    let strx = "0123456789ABCDEF"
    let si = strx.index(of: "A")
    let i = si?.encodedOffset       // i will be an Int. You need "?" because it might be nil, no such character found.

    if i != nil {                   // You MUST deal with the optional, unwrap it only if not nil.
        print("i = ",i)
        print("i = ",i!)            // "!" str1ps off "optional" specification (unwraps i).
            // or
        let ii = i!
        print("ii = ",ii)

    }
    // Good luck.

在swift 2.0中

var stringMe="Something In this.World"
var needle="."
if let idx = stringMe.characters.indexOf(needle) {
    let pos=stringMe.substringFromIndex(idx)
    print("Found \(needle) at position \(pos)")
}
else {
    print("Not found")
}

我知道这是一个旧的答案已经被接受,但你可以找到字符串的索引在几行代码使用:

var str : String = "abcdefghi"
let characterToFind: Character = "c"
let characterIndex = find(str, characterToFind)  //returns 2

一些关于Swift字符串的其他重要信息在这里

斯威夫特3

extension String {
        func substring(from:String) -> String
        {
            let searchingString = from
            let rangeOfSearchingString = self.range(of: searchingString)!
            let indexOfSearchingString: Int = self.distance(from: self.startIndex, to: rangeOfSearchingString.upperBound )
            let trimmedString = self.substring(start: indexOfSearchingString , end: self.count)
            
            return trimmedString
        }
        
    }