How can I check if a string is just one word?
For example "Dog"
, as opposed to "Dog Dog"
.
How can I check if a string is just one word?
For example "Dog"
, as opposed to "Dog Dog"
.
You can do it this way:
let string = "Dog"
if string.components(separatedBy: " ").filter({ !$0.isEmpty}).count == 1 {
print("One word")
} else {
print("Not one word")
}
Let's apply that on " Dog" for example:
First, you need to get the components of the string separated by space, so you'll get:
["", "Dog"]
Then you need to exclude the empty strings by filtering the array.
After that, you only need to check the size of the array, if it's one, then there is only one word.
You can trim and split into an array with a white space character set. than just evaluate the count
let count = string.trimmingCharacters(in: .whitespaces).components(separatedBy: .whitespaces).filter {$0 != ""}.count
switch count {
case 0:
print("no word")
case 1:
print("one word")
default:
print("multiple words")
}