我必须检查文本字段字符串中是否包含数组中的某些 [String],但我只能检查文本字段是否与 [String] 相同。
var array = ["word1", "word2", "word3"]
if //textField.text contains some of the words in the array
{ //do something }
我最近开始学习swift,请帮助我。
最佳答案
这很简单。首先确保在您的 class ViewController: UIViewController{}
之前添加:
import Foundation
然后,您可以像这样找到常用词的数量:
var array = ["word1", "word2", "word3 and word 4"]
var count=0
var s=textField.text!
for item in array{
if s.components(separatedBy: " ").contains(item){
count+=1
}
}
if count > 0{ // do something here
print("There are \(count) in the text field from the array")
}
如果数组包含带空格的元素,则执行如下操作:
var array = ["word1", "word2", "word3"]
var count=0
var s=textField.text!
for item in array{
if s.contains(item){
count+=1
}
}
if count > 0{ // do something here
print("There are \(count) in the text field from the array")
}
说明:
如果找到一个词,变量count
加1。之后,你检查count
是否大于0,如果是,你做什么你想要那里。
最终代码如下所示:
import Foundation
import UIKit
class myClass: UIViewController{
@IBOutlet weak var textField: UITextField!
var array = ["word1", "word2", "word3"]
var count=0
@IBAction func buttonPressed(_ sender: UIButton){
var s=textField.text!
for item in array{
if s.components(separatedBy: " ").contains(item){
count+=1
}
}
if count > 0{
print("There are \(count) in the text field from the array")
}
}
}
希望对您有所帮助!
关于arrays - Swift,字符串检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42749122/