Convert string that is all caps to only only having first letter of each word caps [duplicate] - swift

This question already has answers here:
How to capitalize each word in a string using Swift iOS
(8 answers)
Closed 5 years ago.
I'm getting strings from a server that is all caps like:
"HELLO WORLD"
but I'm trying to make is so each word is caps on its own like:
"Hello World"
I've tried this:
extension String {
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst()).lowercased()
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
but the result is
"Hello world"
any idea on how to do this?

Apple already did that for you:
print("HELLO WORLD".capitalized)
Documentation: https://developer.apple.com/documentation/foundation/nsstring/1416784-capitalized

Related

Swift filter map reduce which option [duplicate]

This question already has answers here:
How to get the first character of each word in a string?
(11 answers)
Closed 1 year ago.
I have quick question about Swift algorithm, assuming I have a string “New Message” which option I need to use to get just initials NM ?
I would use map to get the first character of each word in the string, then use reduce to combine them.
let string = "New Message"
let individualWords = string.components(separatedBy: " ")
let firstCharacters = individualWords.map { $0.prefix(1) }.reduce("", +)
print("firstCharacters is \(firstCharacters)")
Result:
firstCharacters is NM
Edit: Per #LeoDabus' comment, joined is more concise than reduce("", +), and does the same thing.
let firstCharacters = individualWords.map { $0.prefix(1) }.joined()

How do you split a string at every n-th character in Swift? [duplicate]

This question already has answers here:
How to split a string into substrings of equal length
(13 answers)
Closed 4 years ago.
Like the question says, if I have:
XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28
How can I split this string at every 8th character to get:
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSA
Implement this function
extension String {
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
call it this way,
let str = "XQQ230IJFEKJLDSAIOUOIDSAUIFOPDSFE28"
let final = str.inserting(separator: " ", every: 8)
print(final)
Output will be like this,
XQQ230IJ FEKJLDSA IOUOIDSA UIFOPDSF E28
This will be generic solution if you want to add any character instead of space, it will work.

Efficient way to find all instances of Substring within a Swift String [duplicate]

This question already has answers here:
Swift find all occurrences of a substring
(7 answers)
Closed 5 years ago.
Swift 4 apparently has introduced a lot of new changes to String. I'm wondering if there is now a built-in method for finding all instances of a substring within a String.
Here's the kind of thing I'm looking for:
let searchSentence = "hello world, hello"
let wordToMatch = "hello"
let matchingIndexArray = searchSentence.indices(of: "wordToMatch")
'matchingIndexArray' would then be [0, 13]
import Foundation
let searchSentence = "hello world, hello"
var searchRange = searchSentence.startIndex..<searchSentence.endIndex
var ranges: [Range<String.Index>] = []
let searchTerm = "hello"
while let range = searchSentence.range(of: searchTerm, range: searchRange) {
ranges.append(range)
searchRange = range.upperBound..<searchRange.upperBound
}
print(ranges.map { "(\(searchSentence.distance(from: searchSentence.startIndex, to: $0.lowerBound)), \(searchSentence.distance(from: searchSentence.startIndex, to: $0.upperBound)))" })
outputs:
["(0, 5)", "(13, 18)"]

Why does my string cleanup function return the original value? [duplicate]

This question already has an answer here:
Can't replacing string with string
(1 answer)
Closed 7 years ago.
I have made a func so that I easily can make all letters of a string lower case, while also removing all ! and spaces. I made this func (outside of viewdidload)
func cleanLink(linkName: String) -> String {
linkName.stringByReplacingOccurrencesOfString("!", withString: "")
linkName.stringByReplacingOccurrencesOfString(" ", withString: "")
linkName.lowercaseString
return linkName
}
I then used these lines of codes
var theLinkName = cleanLink("AB C!")
print(theLinkName)
The problems is that this is just printing AB C! while I want it to print abc. What am I doing wrong?
The problem is that stringByReplacingOccurrencesOfString returns a new string; it does not perform the replacement in place.
You need to use the return value of the function instead, like this:
func cleanLink(linkName: String) -> String {
return linkName
.stringByReplacingOccurrencesOfString("!", withString: "")
.stringByReplacingOccurrencesOfString(" ", withString: "")
.lowercaseString
}
This "chains" the invocations of functions that produce new strings, and returns the final result of the replacement.

In swift, how do I do this? [duplicate]

This question already has answers here:
Adding Thousand Separator to Int in Swift
(7 answers)
Closed 7 years ago.
My English is not enough to search the question. So, I have to write here. My integer is 600000000 for ex. I want to convert it like this: 600,000,000. How do I do this?
extension Int {
struct Number {
static let formatter = NSNumberFormatter()
}
var addThousandSeparator:String {
Number.formatter.groupingSeparator = "."
Number.formatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
return Number.formatter.stringFromNumber(self)!
}
}
let myInteger = 600000000
let myIntegerString = myInteger.addThousandSeparator // "600.000.000"