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

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

问题描述:

Objective-C 中,检查 NSString 子串的代码是:

In Objective-C the code to check for a substring in an NSString is:

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

但是我如何在 Swift 中做到这一点?

But how do I do this in Swift?

您可以使用 Swift 进行完全相同的调用:

You can do exactly the same call with Swift:

在 Swift 4 中,String 是 Character 值的集合,在 Swift 2 和 3 中不是这样的,因此您可以使用更简洁的代码1:

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 code1:

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

斯威夫特 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")
}

年长的斯威夫特

var string = "hello Swift"

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

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

我希望这是一个有用的解决方案,因为包括我在内的一些人在调用 containsString() 时遇到了一些奇怪的问题.1

I hope this is a helpful solution since some people, including me, encountered some strange problems by calling containsString().1

附注.不要忘记import Foundation

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