Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:String包含String(不使用NSString)?_String_Swift - Fatal编程技术网

Swift:String包含String(不使用NSString)?

Swift:String包含String(不使用NSString)?,string,swift,String,Swift,我在这个问题上也有同样的问题: 但几个月后的今天,我想知道是否可以不使用NSString就完成它? 我很好,简单的包含方法就可以了。 我搜索了网页和文档,但什么也没找到 同样的方法,只需使用Swift语法: let string = "This is a test. This is only a test" if string.rangeOfString("only") != nil { println("yes") } 适用于Swift 3.0 if str.range(of

我在这个问题上也有同样的问题:

但几个月后的今天,我想知道是否可以不使用NSString就完成它? 我很好,简单的包含方法就可以了。
我搜索了网页和文档,但什么也没找到

同样的方法,只需使用Swift语法:

let string = "This is a test.  This is only a test"

if string.rangeOfString("only") != nil {
     println("yes")
}
适用于Swift 3.0

if str.range(of: "abc") != nil{
     print("Got the string")
}

我在SWIFT 3.0的String上写了一个扩展,这样我就可以简单地调用
absoluteString.contains(String:“/kredit/”)


}
String
实际上通过
StringProtocol

不需要任何扩展:

let str = "asdf"
print(str.contains("sd") ? "yep" : "nope")



如果要检查字符串是否与特定模式匹配,我可以推荐有关NSRegularExpressions的NSHipster文章:

,以演示选项的使用

var string = "This is a test.  This is only a test. Not an Exam"

if string.range(of:"ex") != nil {
    print("yes")
}
if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
    print("yes")
}

那么“是”呢,我能得到最后一个“是”吗?@Zam在这种情况下,它将返回
is
的第一个巧合/匹配,如果您打印
范围
,您将得到类似
2
如果let range=string.rangeOfString(“is”){print(range)}
在Swift 2中仍然使用这种语法吗?
rangeOfString
是一种
NSString
方法。@Thyraz它不是:它可能是重复的检查字符串是否包含某个字符@艾米尔马拉什利夫:这是真的。但另外,您可以检查任何符合
StringProtocol
-因此它也适用于
String
。哈,您完全正确,它来自
StringProtocol
var string = "This is a test.  This is only a test. Not an Exam"

if string.range(of:"ex") != nil {
    print("yes")
}
if string.range(of:"ex", options: String.CompareOptions.caseInsensitive) != nil {
    print("yes")
}