所以我对Swift相当新(试图自学),而且我已经陷入困境。我试图创建一个函数,接受一个字符串作为参数,检查第一个元音之前是否有任何辅音,如果是的话,删除它。因此,如果用户输入他的名字作为Michael,那么ichael会打印出来。我写了
func shortNameForName(name: String) -> String {
let shortName = name.lowercaseString
let vowelSet = CharacterSet(charactersIn: "aeiou")
/* I know here i can create an if statement that basically states that if the first
character of the string does not contain the vowelset, remove it, but I don't know
the syntax/how to write it */
return shortName
}
print(shortNameForName("Michael"))
答案 0 :(得分:2)
你可以这样做。
func shortNameForName(name: String) -> String {
let charSet = CharacterSet(charactersIn: "aeiou")
if let index = name.lowercased().rangeOfCharacter(from: charSet)?.lowerBound {
return name.substring(from: index)
}
return ""
}
shortNameForName(name: "Michael")
答案 1 :(得分:0)
使用Swift 3和正则表达式的简单解决方案:
$sql = "SELECT s.*, u.avatar
FROM status AS s
LEFT JOIN users AS u ON u.username = s.author
WHERE s.author IN ('$friendsCSV') AND (s.data LIKE '%#$tag%') AND (s.type='a' OR s.type='c' OR s.type='d')
ORDER BY s.postdate DESC LIMIT 20";
答案 2 :(得分:0)
Swift 3
试试这个
func shortName(for name: String) -> String {
// regular expression for consonants (= not vowels) in the beginning
let regularExpression = "^[^aeiou]+"
guard let firstVowelRange = name.range(
of: regularExpression,
options: [.caseInsensitive, .regularExpression],
range: nil
) else {
return name
}
// if the reg exp matched something, remove it
return name.substring(from: firstVowelRange.upperBound)
}
print(shortName(for: "Michael"))
print(shortName(for: "MMMichael"))
PS:未经测试
答案 3 :(得分:0)
您可以使用NSRegularExpression
编写类似的内容:
func shortNameForName(name: String) -> String {
let pattern = "^[^aeiou]+([aeiou])"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let shortName = regex.stringByReplacingMatches(in: name, range: NSRange(0..<name.utf16.count), withTemplate: "$1")
return shortName //or `shortName.lowercased()` if you prefer
}
print(shortNameForName(name: "Michael")) //->ichael
答案 4 :(得分:0)
Swift 4
func shortNameFromName(_ name: String) -> String {
let lowercaseName = name.lowercased()
let vowelSet = CharacterSet(charactersIn: "aeiou")
if let index = lowercaseName.rangeOfCharacter(from: vowelSet)?.lowerBound {
return String(lowercaseName[index...])
} else {
return lowercaseName
}
}