12

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.

1

11 Answers 11

13

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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
@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.
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 "
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 

1 Comment

Notice that code does not work if your string ends with a whitespace -> "Hello world "
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.

Comments

4

Or by using .reduce():


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

print(desiredOutPut) 

2 Comments

@Montanabucks always happy to help!
Swift 3 Update: var desiredOutPut = String1.components(separatedBy: " ").reduce("") { $0.0 + String($0.1.characters.first!) }
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) } ?? "") } 

Comments

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.

Comments

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"

3 Comments

thanks for helping , and yeah you're am on my track , :) learning , i'll keep this in my mind
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.
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.
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) 

Comments

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) 

1 Comment

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

2 Comments

split String and print first letter of that split strings
this answer is just duplication of any other answer to the OP from 1.5 years ago.
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!)} } } 

Comments