11

I want this:

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 have no idea what to do this with this problem.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    See http://stackoverflow.com/a/25229901/1226963 to split the string into an array of words. – rmaddy Dec 31 '15 at 02:54

11 Answers11

12

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!

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
vien vu
  • 4,277
  • 2
  • 17
  • 30
  • 1
    hey thanks :) @vienvu its working fine , but can you tell me what we are doing here , i mean the codes am not getting how they are performing the task –  Dec 31 '15 at 03:14
  • 2
    @Montanabucks My idea in this case is: We can separate a string to an array by space character. Your gold is get first character each string so we run a loop through this array. We can get first character of it. Because it is character so we need convert to String. We need string to hold result. So each loop we jont it. When end loop we will get result you need. – vien vu Dec 31 '15 at 03:17
  • 1
    Note that this will crash if there is an empty string returned by the `components(separatedBy:)` method. i.e. the original string ends with a whitespace `let stringInput = "First Last "` – Leo Dabus May 04 '21 at 14:46
11

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
Andrei A.
  • 153
  • 1
  • 6
4

Or by using .reduce():


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

print(desiredOutPut)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
dfrib
  • 70,367
  • 12
  • 127
  • 192
4

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.

dchakarov
  • 9,048
  • 3
  • 25
  • 20
3
Note that if you're experiencing error: 

Cannot invoke 'reduce' with an argument list of type '(String, (_) -> _)

labelForContext.text = self.components(separatedBy: " ").reduce("") { first, next in 
     (first) + (next.first.map { String($0) } ?? "")
}
Ty Daniels
  • 99
  • 6
0

You can use the componentsSeparatedByString() method to get an array of strings. Use " " as the separator.

Since you know how to get the first char of a string, now you just do that for each string in the array.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
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

By the way, the convention for variable names I believe is camel-case with a lowercase letter for the first character, such as "string1" as opposed to "String1"

SwiftMatt
  • 949
  • 1
  • 9
  • 19
  • thanks for helping , and yeah you're am on my track , :) learning , i'll keep this in my mind –  Dec 31 '15 at 03:20
  • No problem. It is important to check that first is non-nil, because it can potentially be nil if String1 ends with a space, in which case the final item in the array may be an empty string. – SwiftMatt Dec 31 '15 at 04:37
  • 1
    Here is the excerpt from the Swift programming book: “Whenever you define a new class or structure, you effectively define a brand new Swift type. Give types UpperCamelCase names (such as SomeClass and SomeStructure here) to match the capitalization of standard Swift types (such as String, Int, and Bool). Conversely, always give properties and methods lowerCamelCase names (such as frameRate and incrementCount) to differentiate them from type names.” Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.1 Prerelease).” iBooks. – SwiftMatt Dec 31 '15 at 05:58
0

Here is the changes in swift3

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

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

      print(stringNeed)
Azharhussain Shaikh
  • 1,654
  • 14
  • 17
0

For the sake of completeness this is a solution with very powerful enumerateSubstrings(in:options:_:

let string = "Stack Over Flow"

var result = ""
string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) { (substring, _, _, _) in
    if let substring = substring { result += substring.prefix(1) }
}
print(result)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • substring will never be nil using only `.byWords` option. **The enumerated substring. If substringNotRequired is included in opts, this parameter is nil for every execution of the closure.** `result += substring!.prefix(1) ` if you want to be extra paranoid `result += substring?.prefix(1) ?? ""` – Leo Dabus May 04 '21 at 14:55
0
let inputString = "ABC PQR XYZ"
var stringNeed = ""

class something
{
        let splits = inputString.components(separatedBy: " ")
        for string in splits
        {
            stringNeed = stringNeed + String(string.first!)      
        }
        print(stringNeed)
}
Eugenio
  • 1,013
  • 3
  • 13
  • 33
riya
  • 1
0

Here's the version I used for Swift 5.7 and newer

extension String {
func getAcronym() -> String {
    let array = components(separatedBy: .whitespaces)
    return array.reduce("") { $0 + String($1.first!)}
   }
}
cherucole
  • 560
  • 7
  • 15