Swift中字符串中子字符串的出现次数 [英] Number of occurrences of substring in string in Swift

查看:218
本文介绍了Swift中字符串中子字符串的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主字符串是hello Swift Swift and Swift",子字符串是Swift.我需要获取子字符串Swift"在提到的字符串中出现的次数.

My main string is "hello Swift Swift and Swift" and substring is Swift. I need to get the number of times the substring "Swift" occurs in the mentioned string.

这段代码可以判断模式是否存在.

This code can determine whether the pattern exists.

var string = "hello Swift Swift and Swift"

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

现在我需要知道出现的次数.

Now I need to know the number of occurrence.

推荐答案

一个简单的方法是在 "Swift" 上拆分,然后从零件数中减去 1:

A simple approach would be to split on "Swift", and subtract 1 from the number of parts:

let s = "hello Swift Swift and Swift"
let tok =  s.components(separatedBy:"Swift")
print(tok.count-1)

此代码打印 3.

Swift 3 语法之前,代码如下所示:

Before Swift 3 syntax the code looked like this:

let tok =  s.componentsSeparatedByString("Swift")

这篇关于Swift中字符串中子字符串的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆