How to get the first character of each word in a string?

SWIFT 3

To avoid the crash when there are multiple spaces between words (i.e. John Smith), you can use something like this:

extension String {
  func acronym() -> String {
    return self.components(separatedBy: .whitespaces).filter { !$0.isEmpty }.reduce("") { $0.0 + String($0.1.characters.first!) }
  }
}

If you want to include newlines as well, just replace .whitespaces with .whitespacesAndNewlines.


To keep it more elegant I would make an extension for the swift 3.0 String class with the following code.

extension String
{
    public func getAcronyms(separator: String = "") -> String
    {
        let acronyms = self.components(separatedBy: " ").map({ String($0.characters.first!) }).joined(separator: separator);
        return acronyms;
    }
}

Afterwords you can just use it like this:

  let acronyms = "Hello world".getAcronyms();
  //will print: Hw

  let acronymsWithSeparator = "Hello world".getAcronyms(separator: ".");
  //will print: H.w

  let upperAcronymsWithSeparator = "Hello world".getAcronyms(separator: ".").uppercased();
  //will print: H.W

You can try this code:


let stringInput = "First Last"
let stringInputArr = stringInput.components(separatedBy:" ")
var stringNeed = ""

for string in stringInputArr {
    stringNeed += String(string.first!)
}

print(stringNeed)

If have problem with componentsSeparatedByString you can try seperate by character space and continue in array you remove all string empty.

Hope this help!

Tags:

Ios

Swift