在Swift字符串中查找字符的索引

222

是时候承认失败了...

在Objective-C中,我可以使用类似以下的内容:

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

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

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

...但是它只会给我一个 String.Index,我可以用它来对原始字符串进行下标访问,但无法提取位置。

顺便说一句,那个String.Index有一个私有ivar叫做_position,其中包含了正确的值。我只是不知道它如何被公开。

我知道我可以很容易地将其添加到String中。 我更好奇的是,这个新API中我错过了什么。


这是一个 GitHub 项目,其中包含了许多用于 Swift 字符串操作的扩展方法:https://github.com/iamjono/SwiftString - RenniePet
我找到的最佳实现在这里:https://dev59.com/g1wY5IYBdhLWcg3ws5oF#32306142 - Carlos García
你需要区分Unicode代码点和扩展字形簇吗? - Ky -
33个回答

1

您可以使用以下方法在字符串中查找字符的索引号:

var str = "abcdefghi"
if let index = str.firstIndex(of: "c") {
    let distance = str.distance(from: str.startIndex, to: index)
    // distance is 2
}

0
在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 ""
}

0
let mystring:String = "indeep";
let findCharacter:Character = "d";

if (mystring.characters.contains(findCharacter))
{
    let position = mystring.characters.indexOf(findCharacter);
    NSLog("Position of c is \(mystring.startIndex.distanceTo(position!))")

}
else
{
    NSLog("Position of c is not found");
}

0

我正在使用以下内容进行操作

extension String {
    func allCharactes() -> [Character] {
         var result: [Character] = []
         for c in self.characters {
             result.append(c)
         }
         return 
    }
}

在我理解所提供的内容之前,它只是一个字符数组。

还有:

let c = Array(str.characters)

这意味着什么?你的第一个代码块比第二个更好在哪里? - Ky -

0
如果您只需要一个字符的索引,最简单、最快速的解决方案(如Pascal已经指出的)是:
let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)

字符现在已经被弃用了...遗憾的是,即使它仍然起作用。 - user3069232

0
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

0

0
在Swift 2中获取字符串中子字符串的索引:
let text = "abc"
if let range = text.rangeOfString("b") {
   var index: Int = text.startIndex.distanceTo(range.startIndex) 
   ...
}

0

在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")
}

0

在我的观点里,更好的方式是了解逻辑本身,具体方法如下:

 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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接