I wanted to check if the value array I passed in will be matched or contain the value to the alphabets array, nums array, or both.
the intention of checking this was meant to make a login validation, and I do not want to use the regular expression way to check it, instead I would like to use the current function or loops to solve this question.
the enclosed picture was the approach i have tried. I may have gotten the wrong direction.
Since for character in convertedCharaters
picks each elem of the array, it will either be in alphabets
or in nums
but not in both for sure. That's the mistake in your code.
Here we define to flags (numFound
- true if there was a num, letterFound
- true if there was a letter) and iterate through all elements of the given array.
If the element is contained by alphabets
, we set the result
and set the letterFound = true
. If the for-loop already found a num
, the flag numFound
has to be true
. Therefore we know that we found both (letter and number), so we can instantly return "contains both"
.
Same approach if the element is contained by nums
.
var result = ""
var numFound = false
var letterFound = false
for character in convertedCharaters {
if alphabets.contain(character) {
result = "contains only letter"
letterFound = true
if numFound {
return = "contains both"
}
} else if nums.contains(characters) {
result = "contains only nums"
numFound = true
if letterFound {
return = "contains both"
}
}
}
return result
Be careful about the case that neither num nor letter was found! I did not consider that.