如何检查字符串是否包含Swift中的另一个字符串?

这篇博客讨论了在Swift中如何检查一个字符串是否包含另一个字符串。内容包括不同Swift版本下的解决方案,如使用`contains`方法,以及在不同Swift版本中遇到的问题和解决策略。还介绍了String与Foundation框架的NSString之间的交互,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How do I check if a string contains another string in Swift?

In Objective-C the code to check for a substring in an NSString is: Objective-C中,检查NSString字符串的代码是:

NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
    NSLog(@"exists");
}

But how do I do this in Swift? 但是我如何在Swift中做到这一点?


#1楼

参考:https://stackoom.com/question/1cqLr/如何检查字符串是否包含Swift中的另一个字符串


#2楼

You can just do what you have mentioned: 你可以做你提到的事情:

import Foundation
...
string.contains("Swift");

From the docs: 来自文档:

Swift's String type is bridged seamlessly to Foundation's NSString class. Swift的String类型与Foundation的NSString类无缝桥接。 If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. 如果您正在使用Cocoa或Cocoa Touch中的Foundation框架,除了本章中描述的String功能外,整个NSString API还可用于调用您创建的任何String值。 You can also use a String value with any API that requires an NSString instance. 您还可以将String值与任何需要NSString实例的API一起使用。

You need to import Foundation to bridge the NSString methods and make them available to Swift's String class. 您需要import Foundation来桥接NSString方法并使它们可用于Swift的String类。


#3楼

From the docs, it seems that calling containsString() on a String should work: 从文档中,似乎在String上调用containsString()应该可以工作:

Swift's String type is bridged seamlessly to Foundation's NSString class. Swift的String类型与Foundation的NSString类无缝桥接。 If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. 如果您正在使用Cocoa或Cocoa Touch中的Foundation框架,除了本章中描述的String功能外,整个NSString API还可用于调用您创建的任何String值。 You can also use a String value with any API that requires an NSString instance. 您还可以将String值与任何需要NSString实例的API一起使用。

However, it doesn't seem to work that way. 但是,它似乎没有那样工作。

If you try to use someString.containsString(anotherString) , you will get a compile time error that states 'String' does not contain a member named 'containsString' . 如果您尝试使用someString.containsString(anotherString) ,您将收到一个编译时错误,指出'String' does not contain a member named 'containsString'

So, you're left with a few options, one of which is to explicitly bridge your String to Objective-C by using bridgeToObjectiveC() other two involve explicitly using an NSString and the final one involves casting the String to an NSString 所以,你只剩下几个选项,其中一个是通过使用bridgeToObjectiveC()明确地将你的String桥接到Objective-C,另外两个涉及显式地使用NSString ,最后一个涉及将String转换为NSString

By bridging, you'd get: 通过桥接,你会得到:

var string = "hello Swift"
if string.bridgeToObjectiveC().containsString("Swift") {
    println("YES")
}

By explicitly typing the string as an NSString , you'd get: 通过显式键入字符串作为NSString ,您将获得:

var string: NSString = "hello Swift"
if string.containsString("Swift") {
    println("YES")
}

If you have an existing String , you can initialize an NSString from it by using NSString(string:): 如果您有一个现有的String ,可以使用NSString(string :)从它初始化NSString:

var string = "hello Swift"
if NSString(string: string).containsString("Swift") {
    println("YES")
}

And finally, you can cast an existing String to an NSString as below 最后,您可以将现有String转换为NSString ,如下所示

var string = "hello Swift"
if (string as NSString).containsString("Swift") {
    println("YES")
}

#4楼

Here is my first stab at this in the swift playground. 这是我在快速操场上的第一次尝试。 I extend String by providing two new functions (contains and containsIgnoreCase) 我通过提供两个新函数(contains和containsIgnoreCase)来扩展String

extension String {
    func contains(other: String) -> Bool{
        var start = startIndex

        do{
            var subString = self[Range(start: start++, end: endIndex)]
            if subString.hasPrefix(other){
                return true
            }

        }while start != endIndex

        return false
    }

    func containsIgnoreCase(other: String) -> Bool{
        var start = startIndex

        do{
            var subString = self[Range(start: start++, end: endIndex)].lowercaseString
            if subString.hasPrefix(other.lowercaseString){
                return true
            }

        }while start != endIndex

        return false
    }
}

Use it like this 像这样使用它

var sentence = "This is a test sentence"
sentence.contains("this")  //returns false
sentence.contains("This")  //returns true
sentence.containsIgnoreCase("this")  //returns true

"This is another test sentence".contains(" test ")    //returns true

I'd welcome any feedback :) 我欢迎任何反馈:)


#5楼

You can do exactly the same call with Swift: 您可以使用Swift执行完全相同的调用:

Swift 4 & Swift 5 Swift 4和Swift 5

In Swift 4 String is a collection of Character values, it wasn't like this in Swift 2 and 3, so you can use this more concise code 1 : 在Swift 4中,String是一个Character值的集合,它在Swift 2和3中不是这样的,所以你可以使用这个更简洁的代码1

let string = "hello Swift"
if string.contains("Swift") {
    print("exists")
}

Swift 3.0+ Swift 3.0+

var string = "hello Swift"

if string.range(of:"Swift") != nil { 
    print("exists")
}

// alternative: not case sensitive
if string.lowercased().range(of:"swift") != nil {
    print("exists")
}

Older Swift 年长的斯威夫特

var string = "hello Swift"

if string.rangeOfString("Swift") != nil{ 
    println("exists")
}

// alternative: not case sensitive
if string.lowercaseString.rangeOfString("swift") != nil {
    println("exists")
}

I hope this is a helpful solution since some people, including me, encountered some strange problems by calling containsString() . 我希望这是一个有用的解决方案,因为包括我在内的一些人通过调用containsString()遇到了一些奇怪的问题。 1 1

PS. PS。 Don't forget to import Foundation 不要忘记import Foundation

Footnotes 脚注

  1. Just remember that using collection functions on Strings has some edge cases which can give you unexpected results, eg when dealing with emojis or other grapheme clusters like accented letters. 请记住,在字符串上使用集合函数有一些边缘情况可以给你意想不到的结果,例如在处理表情符号或其他字形集群(如重音字母)时。

#6楼

string.containsString is only available in 10.10 Yosemite (and probably iOS8). string.containsString仅在10.10 Yosemite(可能是iOS8)中可用。 Also bridging it to ObjectiveC crashes in 10.9. 同样将其与10.9中的ObjectiveC崩溃联系起来。 You're trying to pass a NSString to NSCFString. 您正在尝试将NSString传递给NSCFString。 I don't know the difference, but I can say 10.9 barfs when it executes this code in a OS X 10.9 app. 我不知道区别,但是当它在OS X 10.9应用程序中执行此代码时,我可以说10.9 barfs。

Here are the differences in Swift with 10.9 and 10.10: https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/index.html containsString is only available in 10.10 以下是Swift与10.9和10.10的区别: https//developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/index.html containsString仅在10.10中可用

Range of String above works great on 10.9. 上面的字符串范围在10.9上很好用。 I am finding developing on 10.9 is super stable with Xcode beta2. 我发现使用Xcode beta2在10.9上开发是超级稳定的。 I don't use playgrounds through or the command line version of playgrounds. 我不使用游乐场或操场的命令行版本。 I'm finding if the proper frameworks are imported the autocomplete is very helpful. 我发现是否导入了正确的框架,自动完成非常有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值