我的字符串如下:
Apple recipe recapes
Mango Tengaer
Lemone T U
Grapes limoenis Steyic genteur
所以我尝试的是:
if let bakery = filtered?[indexPath.row]{
let stringInput = bakery.fruitsname
let stringInputArr = stringInput.components(separatedBy: " ")
var stringNeed = ""
for string in stringInputArr {
stringNeed = stringNeed + String(string.characters.first!)
}
print(stringNeed) // have to print first word first letter, second word second letter
}
但是当我为我的第3个Lemone T U
字做的时候,我就崩溃了。在这一行:
stringNeed = stringNeed + String(string.characters.first!)
任何帮助!!
由于
Output i expect as per my above words
AR
MT
LT
GL
答案 0 :(得分:2)
只需要检查数组计数
var array = [
"Apple recipe recapes",
"Mango Tengaer",
"Lemone T U",
"Grapes limoenis Steyic genteur"]
for str in array {
let wordArray = str.split(separator: " ")
if wordArray.count >= 2 {
let firstTwoChar = String(wordArray[0].first!)+String(wordArray[1].first!)
print(firstTwoChar)
}
}
输出:
Ar
MT
LT
Gl
答案 1 :(得分:2)
试试这个。它将字符串分隔为字符串数组并删除nil。因此,如果字符串有双倍空格,则过滤掉它。确保字符串至少有2个单词。
if let bakery = filtered?[indexPath.row]{
let stringInput = bakery.fruitsname
if stringInput.components(separatedBy: " ").count >= 2 {
let stringNeed = (stringInput.components(separatedBy: " ").map({ $0.characters.first }).flatMap({$0}).reduce("", { String($0) + String($1) }) as NSString).substring(to: 2)
print(stringNeed)
}
}
答案 2 :(得分:0)
检查第一个字母的可选项可能还有额外的空格
if let bakery = filtered?[indexPath.row]{
let stringInput = bakery.fruitsname
let stringInputArr = stringInput.components(separatedBy: " ")
var stringNeed = ""
for string in stringInputArr {
//Check the optional
if let first = string.characters.first{
stringNeed = stringNeed + String(first)
}
}
}
答案 3 :(得分:0)
试试这个:(我已添加前缀2,因此如果只有单个元素,它将只计算前2个元素,然后不要担心它不会崩溃)
if let bakery = filtered?[indexPath.row]{
let stringInput = bakery.fruitsname
let stringInputArr = stringInput.components(separatedBy: " ")
var stringNeed = ""
for string in stringInputArr.prefix(2) //returns only first two elements {
if let strFirst = string.characters.first{
stringNeed += String(strFirst)
}
}
}
答案 4 :(得分:0)
这是我的解决方案,事实上您已经启动了一个String对象数组。
let myStrings:[String] = ["Apple recipe recapes","Mango Tengaer", " Lemone T U", "Grapes limoenis", "Steyic genteur", "He"]
var retStr = "";
for (_, str) in myStrings.enumerated()
{
let stringInOneLine = str.components(separatedBy: CharacterSet.whitespaces).filter({$0.count > 0}).map({String($0.first!).uppercased()}).prefix(2).joined()
//Separate all components by white spaces
let c1 = str.components(separatedBy: CharacterSet.whitespaces)
print("c1: \(c1)")
//Remove components that are empty: It happens in case there is double spaces for instance
let c2 = c1.filter({$0.count > 0})
print("c2: \(c2)")
//Get only the first letter and in upper case
let c3 = c2.map({String($0.first!).uppercased()})
print("c3: \(c3)")
//Keep only the first two elements (if there is more or less than 2, it's takend care of
let c4 = c3.prefix(2)
print("c4: \(c4)")
//Reform the String with the first letters
let string = c4.joined()
print("string: \(string)")
retStr.append(stringInOneLine)
retStr.append("\n")
print("stringInOneLine:\n\(stringInOneLine)")
}
print("retStr:\n\(retStr)")
如果需要可以轻松更改构造retStr
的方式(如果你想要一个String数组)。
我通过解释为什么要进行每次调用来分解stringInOnLine
构造。
这取决于您的Swift专业水平和全局编程/算法技能,以决定您是否更喜欢所有链接在一行中或在各行中执行。
它有助于说明如何分解链式调用(调试,理解或创建它们)。
答案 5 :(得分:0)
var input: [String] = ["apple recipe recapes", "Mango Tengaer", "Lemone T U", "Grapes limoenis Steyic genteur", "One", "A B"]
var result = input.filter { $0.contains(" ") && $0.characters.count > 0 }.map { String($0.first!).uppercased() + $0.substring(with: $0.range(of: "( \\w{1})", options: .regularExpression, range: $0.startIndex..<$0.endIndex)!).uppercased().trimmingCharacters(in: CharacterSet(charactersIn: " ")) }
并且实际的result
是:
["AR", "MT", "LT", "GL", "AB"]
注意: 它会忽略单个单词或空字符串,但您也可以将它扩展为那些,我认为,如果是要求,它不处理只有空格的输入字符串,正如您在测试中看到的那样。
答案 6 :(得分:0)
如果句子中只有两个单词,这应该可以工作。
String(fullName.components(separatedBy: " ").compactMap { $0.first })
答案 7 :(得分:0)
这应该适用于 Swift 4
String(actualString.components(separatedBy: " ").compactMap { $0.first }).uppercased()