arrays - Swift,字符串检查

标签 arrays swift text

我必须检查文本字段字符串中是否包含数组中的某些 [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/

相关文章:

arrays - 如何在 C 编程中将 char 数组转换为 int 数组?

java - 我的 if 语句每次都返回错误的值,是我的数组吗?

swift mapkit 当前位置

使用链表计算 C 中未知但巨大的文本文件中的单词数

c++ - 如何删除 C++ std::string 中的重音符号和波浪号

c++ - 使用位集在不使用循环的情况下获取数组项的条件和

c - 返回指向指针数组的指针

c# - 如何在 iOS 上访问用户的 MKAnnotationView

ios - MagicalRecord saveWithBlock 用法现在无法在 XCode 7 beta 5 下编译

python - Pygame 文本换行符