Check if Swift String is one word [duplicate] - swift

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.

Related

How to check if a string contains a substring within an array of strings in Swift?

I have a string "A very nice beach" and I want to be able to see if it contains any words of the substring within the array of wordGroups.
let string = "A very nice beach"
let wordGroups = [
"beach",
"waterfront",
"with a water view",
"near ocean",
"close to water"
]
First solution is for exactly matching the word or phrase in wordGroups using regex
var isMatch = false
for word in wordGroups {
let regex = "\\b\(word)\\b"
if string.range(of: regex, options: .regularExpression) != nil {
isMatch = true
break
}
}
As suggested in the comments the above loop can be replace with a shorter contains version
let isMatch = wordGroups.contains {
string.range(of: "\\b\($0)\\b", options: .regularExpression) != nil
}
Second solution is for simply text if string contains the any of the strings in the array
let isMatch2 = wordGroups.contains(where: string.contains)
So for "A very nice beach" both returns true but for "Some very nice beaches" only the second one returns true
Wasn't too sure how to interpret "to see if it contains any words of the substring within the array of wordGroups", but this solution checks to see if any words of your input string are contained in any substring of your word groups.
func containsWord(str: String, wordGroups: [String]) -> Bool {
// Get all the words from your input string
let words = str.split(separator: " ")
for group in wordGroups {
// Put all the words in the group into set to improve lookup time
let set = Set(group.split(separator: " "))
for word in words {
if set.contains(word) {
return true
}
}
}
return false
}

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

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

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

Issue in removing spaces from string in swift [duplicate]

This question already has answers here:
How should I remove all the leading spaces from a string? - swift
(31 answers)
Closed 4 years ago.
i'm getting my contacts number locally from my mobile. There are some number in which there are white spaces between numbers. I'm trying to remove the white spaces from the number but it isn't working,this is how i'm removing the white spaces,
let number = contact.phoneNumbers.first?.value.stringValue
let formattedString = number?.replacingOccurrences(of: " ", with: "")
print(formattedString)
But when i print this is what i got in the console,
+92 324 4544783
The white sapces are still coming how can i remove that?
Here you go: source
For trimming white spaces from both ends, you can use:
let number = contact.phoneNumbers.first?.value.stringValue
let formattedString = number.trimmingCharacters(in: .whitespacesAndNewlines)
print(formattedString)
For removing whitespaces that might be inside the string, use:
let x = "+92 300 7681277"
let result = x.replacingOccurrences(of: " ", with: "")
You should get:
result = +923007681277
EDIT: I updated my answer.
let number = contact.phoneNumbers.first?.value.stringValue
let number_without_space = number.components(separatedBy: .whitespaces).joined()
print(number_without_space) //use this variable wherever you want to use
joined() is a function it will join your string after removing spaces like this
let str = "String Name"
str.components(separatedBy: .whitespaces).joined()
extension to remove spaces
extension String
{
func removeSpaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
}

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!