Swift filter map reduce which option [duplicate] - swift

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()

Related

How to replace a substring in a string in Swift [duplicate]

This question already has answers here:
Any way to replace characters on Swift String?
(23 answers)
Closed 2 years ago.
my code is like the following:
let fileName = "/users/lezi/downloads/Zootopia.srt"
var srtFile = try? String(contentsOfFile: fileName)
let range = srtFile?.range(of: "00:00:59,825")
print(srtFile?[range!])
srtFile?.replaceSubrange(range!, with: "00:00:59,826")
print(srtFile?[range!])
I hope the "00:00:59,825" is replaced to "00:00:59,826", but the print is "Optional("\r\n\r\n2")\n", some characters just before "00:00:59,825"
Regardless of use case. The common syntax to replace the substring is:
str.replacingOccurrences(of: "replace_this", with: "with_this")
where replace_thisis the text string you want to replace and ```with_this`` is the new sub-string to insert.
You can try using replacingOccurrences(of:with:).
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string
sample example :
let str = "Swift 4.0 is the best version of Swift to learn, so if you're starting fresh you should definitely learn Swift 4.0."
let replaced = str.replacingOccurrences(of: "4.0", with: "5.0")

How can I count the number of sentences in a given text in Swift? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I wanted to create a playground that would count the number of sentences of a given text.
let input = "That would be the text . it hast 3. periods. "
func sentencecount() {
let periods = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
let periods = input.components(separatedBy: spaces)
let periods2 = Int (words.count)
print ("The Average Sentence length is \(periods2)")
}
sentencecount()
You can use enumerateSubstrings(in: Range) and use option .bySentences:
let input = "Hello World !!! That would be the text. It hast 3 periods."
var sentences: [String] = []
input.enumerateSubstrings(in: input.startIndex..., options: .bySentences) { (string, range, enclosingRamge, stop) in
sentences.append(string!)
}
An alternative is to use an array of Substrings instead of Strings:
var sentences: [Substring] = []
input.enumerateSubstrings(in: input.startIndex..., options: .bySentences) { (string, range, enclosingRamge, stop) in
sentences.append(input[range])
}
print(sentences) // "["Hello World !!! ", "That would be the text. ", "It hast 3 periods."]\n"
print(sentences.count) // "3\n"
This should work :
let input = "That would be the text . it hast 3. periods. "
let occurrencies = input.characters.filter { $0 == "." || $0 == "?" }.count
print(occurrencies)
//result 3
Just add the character in charset by which you are going to differentiate your sentences:
I am assuming ? . , for now:
let input = "That would be the text. it hast 3? periods."
let charset = CharacterSet(charactersIn: ".?,")
let arr = input.components(separatedBy: charset)
let count = arr.count - 1
Here arr would be:
["That would be the text", " it hast 3", " periods", ""]
decrease count by 1, to get actual sentences.
Note: If you don't want to consider " , " then remove it from charset.
As far as i can see that you need to split them using . and trimming whitespaces as the following:
func sentencecount () {
let result = input.trimmingCharacters(in: .whitespaces).split(separator: ".")
print ("The Average Sentence length is \(result.count)") // 3
}
Good luck!

Parsing a string to get last name in Swift [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 5 years ago.
I'm writing a app where I need to present the second name of a person on the screen.
The names are always "firstname space lastname" as in:
let str = "Fred Bloggs"
let secondStr = "William Wright"
Can you tell me how to get "Bloggs" out of that first string and "Wright" out of the second string, not knowing the index of Bloggs. All the examples I've seen seem to assume you know the index of the position you want to get a substring from.
Thanks.
import Foundation
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]
let lastName = fullNameArr[1]

Reversing a string in Swift [duplicate]

This question already has answers here:
Reversing the order of a string value
(13 answers)
Closed 5 years ago.
Needed to reverse a swift string, managed to do so with this.
var str = "Hello, playground"
let reactedText = str.characters.reversed()
let nowBackwards = Array(reactedText)
let answer = String(nowBackwards)
And since I find nothing on SO in the subject I post it for some positive votes :) or indeed a better [shorter, as in different] solution.
Assuming you are using Swift 4 :
let string = "Hello, playground"
let reversedString = String(string.reversed())
Since in Swift 4, Strings are Character arrays again, you can call reversed on the String itself and the result will be of type [Character], from which you can initialize a String.
let stringToBeReversed = "Hello, playground"
let reversedString = String(stringToBeReversed.reversed()) //"dnuorgyalp ,olleH"
reversed method is available in String library
let str = "Hello, world!"
let reversed = String(str.reversed())
print(reversed)

Split string after found symbol # or number in swift ios [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 6 years ago.
I want get value before symbol # or number in swift. I have email which is john#gmail.com. I want get john only. Another example is peter34#gmail.com. I want get peter only.
Use components(separatedBy:) passing it a CharacterSet composed of # and the digits, and then use first to get the first part of the symbol:
let emails = ["john#gmail.com", "peter34#gmail.com"]
for email in emails {
if let name = email.components(separatedBy: CharacterSet(charactersIn: ("#0123456789"))).first {
print(name)
}
}
Output:
john
peter
try this
let EMAIL= "peter34#gmail.com"
let EMAILARR= EMAIL.characters.split{$0 == "#"}.map(String.init)
EMAILARR[0] // to get peter34
EMAILARR[1] // to get gmail.com