如何检查字符串是否只有一个字?
例如"Dog"
,而不是"Dog Dog"
。
答案 0 :(得分:2)
你可以这样做:
let string = "Dog"
if string.components(separatedBy: " ").filter({ !$0.isEmpty}).count == 1 {
print("One word")
} else {
print("Not one word")
}
我们将其应用于“狗”,例如:
首先,你需要用空格分隔字符串的组件,这样你才能得到:
[“”,“狗”]
然后你需要通过过滤数组来排除空字符串。
之后,您只需要检查数组的大小,如果是1,那么只有一个单词。
答案 1 :(得分:2)
您可以修剪并拆分为具有空白字符集的数组。而不仅仅是评估计数
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")
}