Find number of spaces in a string in Swift
Swift 5 or later
In Swift 5 we can use the new Character properties isWhitespace and isNewline
let str = "Hello, playground. Hello, playground !!!"
let spaceCount = str.reduce(0) { $1.isWhitespace && !$1.isNewline ? $0 + 1 : $0 }
print(spaceCount) // 4
If your intent is to count " "
only
let spaceCount = str.reduce(0) { $1 == " " ? $0 + 1 : $0 }
Swift - Whitespace count in a string
If you want to consider other whitespace characters (not only space) use regular expression:
let string = "How to get count of the empty space in text,Like how we get character count like wise i need empty space count in a text, It would be more helpful if explained with an example."
let regex = try! NSRegularExpression(pattern: "\\s")
let numberOfWhitespaceCharacters = regex.numberOfMatches(in: string, range: NSRange(location: 0, length: string.utf16.count))
Regular expression \\s
considers tab, cr, lf and space
How to count number of leading spaces in a string in Swift?
One way is to use prefix(while:)
, and count how many characters you got:
yourString.prefix(while: { $0 == " " }).count
How can i find character number except space between words
let str = "Hello I m iOS developer"
let filter = str.filter {!$0.isWhitespace}
print(filter.count)
Swift - How do I count the occurrences of a specific character in a String?
To count the occurrences of a specific character all you have to do is use the filter() method like so:
var myName = "Jane Doe"
let numOccurrences = myName.filter{ $0 == "e" }.count
print(numOccurrences) // prints out 2
.filter
will iterate over every character in the string, denoted by $0
, and then return a list of all characters that are equal to the character "e". All you have to do after that is use .count
to get the number of total occurrences.
Check if string has a space
let url = "http://www.example.com/images/pretty pic.png"
let whiteSpace = " "
if let hasWhiteSpace = url.rangeOfString(whiteSpace) {
print ("has whitespace")
} else {
print("no whitespace")
}
How can I check to see if a string contains characters of whitespace/alphanumeric/etc?
Use NSCharacter on the entire string,not character-by-character:
let whitespace = NSCharacterSet.whitespaceCharacterSet()
let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(whitespace)
// range will be nil if no whitespace is found
if let test = range {
println("whitespace found")
}
else {
println("whitespace not found")
}
Output:
whitespace found
How to remove all the spaces and \n\r in a String?
Swift 4:
let text = "This \n is a st\tri\rng"
let test = String(text.filter { !" \n\t\r".contains($0) })
Output:
print(test) // Thisisastring
While Fahri's answer is nice, I prefer it to be pure Swift ;)
String to Double and leading whitespace
This is fully documented. Look at the documentation for the init
method that takes a StringProtocol
.
Near the end of all of the examples, it states:
Passing any other format or any additional characters as
text
results innil
. For example, the following conversions result innil
:Double(" 5.0") // Includes whitespace
So your solution to trim whitespace before conversion is the correct one.
Related Topics
Removing Parentheses from The String in iOS
iOS 8 Code Working on iPhone 5S But Not iPhone 5
Detect Array with Issue (Debug Mode)
Ckfetchnotificationchangesoperation Sometimes Does Not Return Update, Delete Notifications
Can't Build an App for Distribution After Joining Existing Enterprise Developer Program
Multiple Async Requests at Once in Objective C
Screenshot on Swift Programmatically
How to Access All Images in a .Xcassets at Once
Camera Only Takes Pictures in Portrait Mode Swift
Testflight Sdk and iOS Simulator - How to Use
Set Custom Font for UItableview Swipe Action (Uicontextualaction)
How to Check a App Was Installed or Updated
Checking Cellular Network Type in iOS