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

I want it:

var String1 = "Stack Over Flow"
var desiredOutPut = "SOF" // the first Character of each word in a single String (after space)

I know how to get the first character from a string, but I don't know what to do with this problem.

+4
source share
7 answers

You can try this code:

let stringInput = "First Last"
let stringInputArr = stringInput.componentsSeparatedByString(" ")
var stringNeed = ""

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

print(stringNeed)

If you have a problem with componentsSeparatedByString, you can try separately from the character space and continue in the array, you will delete the entire line blank.

Hope this help!

+4
source

To make it more elegant, I would make an extension to the String 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;
    }
}

Afterword you can simply use it as follows:

  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
+4
source

.reduce():

let str = "Stack Over Flow"
let desiredOutPut = str
    .components(separatedBy: " ")
    .reduce("") { $0.0 + ($0.1.characters.first.map(String.init(_:)) ?? "") }

let desiredOutPut = str
    .components(separatedBy: " ")
    .reduce("") { $0.0 + ($0.1.characters.first.map{ String($0) } ?? "") }
+3

SWIFT 3

(.. John Smith), - :

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

, .whitespaces .whitespacesAndNewlines.

+1
0
var String1 = "Stack Over Flow"
let arr = String1.componentsSeparatedByString(" ")
var desiredoutput = ""
for str in arr {
    if let char = str.characters.first {
        desiredoutput += String(char)
    }
}
desiredoutput

, , , , , "string1", "String1"

0

swift3

      let stringInput = "Stack Overflow"
      let stringInputArr = stringInput.components(separatedBy: " ")
      var stringNeed = ""

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

      print(stringNeed)
0
source

Source: https://habr.com/ru/post/1622300/


All Articles