从前两个单词的字符串中获取第一个字母

Getting first letter from the string of first two words

我的字符串像:

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

}

但是对我来说,当我第三次Lemone T Uwords.On这条线时,我在这条线上崩溃了:

 stringNeed = stringNeed + String(string.characters.first!)

任何帮助!!

谢谢

Output i expect as per my above words


AR
MT
LT
GL

检查第一个字母的可选可能有额外的 space 添加到它

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)

                }
            }

}

只需要检查数组计数

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

试试这个:(我添加了前缀 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)
               }
        }

}

试试这个。它将字符串分成字符串数组并删除 nil。因此,如果字符串有双 space 它会过滤掉它。确保字符串至少包含 2 个单词。

if let bakery = filtered?[indexPath.row]{
   let stringInput = bakery.fruitsname
   if stringInput.components(separatedBy: " ").count >= 2 {
         let stringNeed = (stringInput.components(separatedBy: " ").map({ [=10=].characters.first }).flatMap({[=10=]}).reduce("", { String([=10=]) + String() }) as NSString).substring(to: 2)
    print(stringNeed)  
  }
}

这是我的解决方案,事实上您在开始时拥有一个 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({[=10=].count > 0}).map({String([=10=].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({[=10=].count > 0})
    print("c2: \(c2)")

    //Get only the first letter and in upper case
    let c3 = c2.map({String([=10=].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 如果需要可以轻松更改(例如,如果您想要一个字符串数组)。 我通过解释每个调用的原因来分解 stringInOnLine 结构。 这取决于您的 Swift 专业水平和全球 programming/algorithm 技能来决定您是喜欢将所有内容链接在一行中还是在多行中进行。 它有助于说明如何分解链式调用(以调试、理解或创建它们)。

乍一看可能有点奇怪,但它确实为您完成了工作(我并不是说它是最有效的解决方案):

var input: [String] =  ["apple recipe recapes", "Mango Tengaer", "Lemone  T U", "Grapes   limoenis   Steyic genteur", "One", "A B"]
var result = input.filter { [=10=].contains(" ") && [=10=].characters.count > 0 }.map { String([=10=].first!).uppercased() + [=10=].substring(with: [=10=].range(of: "( \w{1})", options: .regularExpression, range: [=10=].startIndex..<[=10=].endIndex)!).uppercased().trimmingCharacters(in: CharacterSet(charactersIn: " ")) }

而实际的result是:

["AR", "MT", "LT", "GL", "AB"]

注意: 它会忽略单个单词或空字符串,但我想你也可以为它们扩展它,如果这是要求,它不处理只有空格的输入字符串,正如您在测试中看到的那样。

如果句子中只有两个词,这应该有效。

String(fullName.components(separatedBy: " ").compactMap { [=10=].first })

这应该适用于 Swift 4

String(actualString.components(separatedBy: " ").compactMap { [=10=].first }).uppercased()