Search code examples
iosswiftstringxcode9

Getting first letter from the string of first two words


My string like :

Apple recipe  recapes

Mango Tengaer

Lemone T U

Grapes limoenis  Steyic genteur

So what i tried is :

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

}

But for me crash on this line when i do for my 3rd Lemone T U words.On this line:

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

Any help !!

Thanks

Output i expect as per my above words


AR
MT
LT
GL

Solution

  • Try this. It separates the string into array of string and removes nil. So if the string has double space it filters that. Make sure that the string has minimum 2 words.

    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)  
      }
    }