Swift – How to find out if a string contains several identical characters? [duplicate] - swift

This question already has answers here:
Number of occurrences of substring in string in Swift
(12 answers)
how to count specific items in array in swift
(3 answers)
Closed 3 years ago.
Here's a simple code that let us find out if a string contains a dot characters (we don't know how many, we just know that it contains it):
var number: String = "3.14"
if number.contains(".") {
print("The string contains a dot character")
} else {
print("There's no dot character")
}
But imagine a situation where user wrongly puts 2 or 3 dots in a line, like this:
var number: String = "3...14"
How to check whether a string contains one dot or several ones?
How to count all the dots in the string?

You can use filter(_:) on the string and count to get the number of dots:
let str = "3..14"
switch str.filter({ $0 == "." }).count {
case 0:
print("string has no dots")
case 1:
print("string has 1 dot")
default:
print("string has 2 or more dots")
}

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.

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]

Check if Swift String is one word [duplicate]

This question already has answers here:
Number of words in a Swift String for word count calculation
(7 answers)
Closed 5 years ago.
How can I check if a string is just one word?
For example "Dog", as opposed to "Dog Dog".
You can trim and split into an array with a white space character set. than just evaluate the count
let count = string.trimmingCharacters(in: .whitespaces).components(separatedBy: .whitespaces).filter {$0 != ""}.count
switch count {
case 0:
print("no word")
case 1:
print("one word")
default:
print("multiple words")
}
You can do it this way:
let string = "Dog"
if string.components(separatedBy: " ").filter({ !$0.isEmpty}).count == 1 {
print("One word")
} else {
print("Not one word")
}
Let's apply that on " Dog" for example:
First, you need to get the components of the string separated by space, so you'll get:
["", "Dog"]
Then you need to exclude the empty strings by filtering the array.
After that, you only need to check the size of the array, if it's one, then there is only one word.

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