将String与String数组进行比较,并在Swift中计算匹配项

时间:2018-08-01 01:20:38

标签: arrays swift string-matching

我正在尝试将一个字符串(userInput)与一个字符串数组(groupA)比较,以检查userInput中存在groupA中有多少项。

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."
var count = 0

func checking() -> Int {
    for item in groupA {
        // alternative: not case sensitive
        if userInput.lowercased().range(of:item) != nil {
            count + 1
        }
    }

    return count
}

func Printer() {
     print(count)
}

2 个答案:

答案 0 :(得分:1)

由于您使用了很多全局变量,因此您的代码设计得不太好,但是可以进行一些小的更改:

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."

var count = 0
func checking() -> Int {
    for item in groupA {

        // alternative: not case sensitive
        if userInput.lowercased().range(of:item) != nil {
            count += 1  //Make this `count += 1`
        }
    }
    return count
}
func printer() {
    print(count)
}

//Remember to call `checking()` and `printer()`
checking()
printer()

还要注意,您应以小写字母命名所有函数,因此Printer()应该为printer()

请考虑以下代码:

import UIKit

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."

//The `checking` function has been rewritten as `countOccurerences(ofStringArray:inString)`, 
//and now takes parameters and returns a value.
func countOccurrences(ofStringArray stringArray: [String],  inString string: String) -> Int {
    var result = 0
    for item in stringArray {

        // alternative: not case sensitive
        if string.lowercased().range(of:item) != nil {
            result += 1
        }
    }
    return result
}

//And the `printer()` function now takes parameter as well.
func printer(_ count: Int) {
    print("count = \(count)")
}

//Here is the code to use those 2 functions after refactoring
let count = countOccurrences(ofStringArray: groupA, inString: userInput)
printer(count)

答案 1 :(得分:0)

要使上述代码正常工作,只需将第18行中的count + 1更改为count += 1,我已在下面发布了完整的代码。

import Cocoa
import Foundation

var groupA = ["game of thrones", "star wars", "star trek" ]
var userInput = "My name is oliver i love game of thrones, star wars and star trek."


    var count = 0
    func checking() -> Int {


        for item in groupA {


            // alternative: not case sensitive
            if userInput.lowercased().range(of:item) != nil {
                count += 1
            }


        }

        return count
    }



    func Printer() {
        print(count)
    }

    checking()
    Printer()