
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove All Whitespace from a String in Swift
A whitespace character is a non-printable character which represents a space in the string. To remove all the whitespaces from a string Swift provides the following methods ?
Using isWhitespace Property
Using component() function
Using replacingOccurrences(of:with:) method
Using regular expressions
Method 1: Using isWhitespace Property
isWhitespace property is used to check whether the given character is a whitespace character or not. In this method, we use the isWhitespace property with the filter() method to remove all the whitespaces present in the given string.
Syntax
var res = str.filter{!$0.isWhitespace}
Here, the filter() method is called on the str string. The closure(!$0.isWhitespace) passed in the function checks each character in the string and returns true if the character is not a whitespace character.
Example
In the following Swift program, we will remove all whitespaces from a string. So for that, we create a function which takes a string as input. Then the function uses the filter() method with !$0.isWhitespace closure on the entered string to check characters one by one if they are whitespace characters or not. If yes, then delete that character and store the non-whitespace characters into a variable. After removing all the whitespaces the remaining characters converts back into the string using the String() initializer and return the function returns the final string with no whitespaces.
import Foundation import Glibc func removeWhitespacesFromString(mStr: String) -> String { let filteredChar = mStr.filter { !$0.isWhitespace } return String(filteredChar) } let input = "Mohan learn swift programming" let resStr = removeWhitespacesFromString(mStr: input) print("Original String:", input) print("String without whitespaces:", resStr)
Output
Original String: Mohan learn swift programming String without whitespaces: Mohanlearnswiftprogramming
Method 2: Using components() method
The components() method is used to create an array of substrings from the given string, where each substring is separated by the specified separator. So here we use the components(separatedBy:.whitespaces) method with .wihitespaces as a parameter to create an array of substrings in which the substrings are separated by a whitespace character. After that, we use joined() function to join all the substrings into a string without any whitespace.
Syntax
str.components(separatedBy:.whitespaces)
Here, the component() method is called on the str string and returns an array of substrings separated by whitespaces.
Example
In the following Swift program, we will remove all whitespaces from a string. So for that, we create a function which takes a string as input. Then the function uses the components(separatedBy: .whitespaces) method to convert the input string into the array of substrings based on the whitespaces. Then it uses joined() method to join all the substrings into a string with no whitespaces.
import Foundation import Glibc func removeWhitespacesFromString(mStr: String) -> String { let chr = mStr.components(separatedBy: .whitespaces) let resString = chr.joined() return resString } let input = "Today is the rainy day" let resStr = removeWhitespacesFromString(mStr: input) print("Original String:", input) print("String without whitespaces:", resStr)
Output
Original String: Today is the rainy day String without whitespaces: Todayistherainyday
Method 3: Using replacingOccurrences() method
The replacingOccurrences() method is used to replace all the occurrences of the specified character with the given character. So here we replace all the occurrences of the whitespace character(" ") with the empty string("") to remove all the whitespaces from the string.
Syntax
func replacingOccurrences{of: tchar, with: rchar}
Here, this function takes two arguments one is the tchar which is a character which we want to replace and rchar is the replacement character to which we replace tchar.
Example
In the following Swift program, we will remove all whitespaces from a string. So for that, we create a string, then use replacingOccurrences(of:with:) method and replace whitespace(" ") with an empty string("") and return a new string without whitespaces. Finally, we will display the output.
import Foundation import Glibc let input = "Siya run a beautiful car" let resultantString = input.replacingOccurrences(of: " ", with: "") print("Original string:", input) print("String without whitespaces:", resultantString)
Output
Original string: Siya run a beautiful car String without whitespaces: Siyarunabeautifulcar
Method 4: Using Regular Expression
We can also remove all the whitespaces from the string using regular expressions. Here we use stringByReplacingMatches() function of NSRegularExpression class to remove all white spaces.
Example
In the following Swift program, we will remove all whitespaces from a string. So for that, we create a string, then we create an instance of NSRegularExpression class with "\s" pattern. Where "\s" pattern is used to match the whitespace character. Then we use stringByReplacingMatches() function to replace all the occurrences of whitespace with empty strings. Finally, we get the string without whitespaces.
import Foundation import Glibc let input = "Siya run a beautiful car" let regexValue = try! NSRegularExpression(pattern: "\\s", options: []) let newString = regexValue.stringByReplacingMatches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count), withTemplate: "") print("Original String:", input) print("String without whitespaces:", newString)
Output
Original String: Siya run a beautiful car String without whitespaces: Siyarunabeautifulcar
Conclusion
So this is how we can remove all whitespaces from a string. You can use any of the above methods to remove all whitespaces from the string. All the methods do their job very well. Removing of whitespaces from the string is useful in data validation, formatting, comparison and searching, parsing, etc.