Swift Program to Replace the Spaces of a String with a Specific Character


In Swift, we are allowed to replace whitespaces with the specified character like $, *, ! etc. So, to replace the spaces of a string with a specific character swift provide the following methods −

  • Using replacingOccurrences() method

  • Using user-defined method

  • Using components() and joined() methods

  • Using split() and joined() methods

  • Using map() and joined() method

Method 1: Using the replacingOccurrences() method

The replacingOccurrences() method is used to create a string in which all the occurrences of the target string or character are replaced by the specified string or character.

Syntax

func replacingOccurrences(of: String, with: String) 

Here, the replacingOccurrences() method takes two parameters in which the “of” parameter is the target string which needs to replace and the “with” parameter contains the replacement string, it is the string which replaces the target string.

Example

In the following Swift program, we will replace the space of a string with a specific character. So for that, we create a function with takes the input string and the replacement character. Then this function calls replacingOccurrences(of: " ", with: String(replacementChar)) on the input string and replaces all the whitespaces with a “^” character and returns the updated string.

import Foundation
import Glibc
func replaceSpacesToChar(mstr: String,
replacementChar: Character) -> String {
   let resultantString = mstr.replacingOccurrences(of: " ", with: String(replacementChar))
   return resultantString
}
let StringVal = "Pen color is Blue"
let replacedStr = replaceSpacesToChar(mstr:StringVal,
replacementChar: "^")
print("Original String: ", StringVal)
print("String after replacing spaces with \"^\":", replacedStr)

Output

Original String:  Pen color is  Blue
String after replacing spaces with "^": Pen^color^is^^Blue

Method 2: Using a user-defined method

We can also replace the spaces of a string with a specific character without using a predefined function. We can create a function in which we iterate through each character of the given string using a for-in loop and check if the current character is equal to whitespace. If yes, then append the specified character in the new string. If not, then append the non-whitespace character in the new string.

Example

In the following Swift program, we will replace the space of a string with a specific character. So for that, we create a function with takes the input string and the replacement character. Then this function creates an empty string to store the result. Then it runs a for-in loop to iterate through each character of the given string, and check if the current character is whitespace or not. If yes, then it appends the replacement character(“#”) in the new string. Otherwise, it appends the original character in the new string. After iterating through all the characters of the input string it returns the final modified string.

import Foundation
import Glibc
func replaceSpacesWithChar(str: String, newChar:
Character) -> String {
   var resultantStr = ""

   for character in str {
      if character == " " {
         resultantStr.append(newChar)
      } else {
         resultantStr.append(character)
      }
   }
   return resultantStr
}
let enteredStr = "Mohan buys veggies from supermarket"
let modifiedStr = replaceSpacesWithChar(str: enteredStr, newChar: "#")
print("Original string: ", enteredStr)
print("Modified string after replacing spaces with\"#\":", modifiedStr)

Output

Original string:  Mohan buys veggies from   supermarket
Modified string after replacing spaces with "#": Mohan#buys#veggies#from###super-market

Method 3: Using the components() and joined() methods

To replace the spaces of a string with a specific character we first divide the string into an array of substring where each substring is separated by whitespace characters using the components(separatedBy:) method. Then we join all the elements of the arrays with the specified character using joined(separator:) method.

Example

In the following Swift program, we will replace the space of a string with a specific character using components() and joined() methods. So for that, we create a string, then using components(separatedBy:” “) we create an array of substrings. Then we convert the array of substrings back into the string using joined(separator: “%”) function where each substring is joined by using “%”. And finally we display the output.

import Foundation
import Glibc
let StringVal = "Ball Pen color is Black"
print("Original String: ", StringVal)

// Converting string into an array of substrings
let arraySubstring =
StringVal.components(separatedBy:" ")

// Converting array of substring back in string where
// each whitespace character is replaced by %
let resString = arraySubstring.joined(separator: "%")
print("String after replacing spaces with \"%\":",
resString) 

Output

Original String:  Ball Pen color is  Black
String after replacing spaces with "%": Ball%Pen%color%is%%Black

Method 4: Using split() and joined() methods

We can also replace the spaces of a string with a specific character with the help of split() and joined() methods. Where split(separator:omittingEmptySubsequences:) method is used to convert the given string into the array of substrings. Then using joined() method we will join all the elements of the arrays with the specified character using joined(separator:) method to create the resultant string.

Example

In the following Swift program, we will replace the space of a string with a specific character using split() and joined() methods. So for that, we create a string, then using split(separator:omittingEmptySubsequences:) method we split the input string into an array of substrings according to the whitespace character.Then we convert the array of substrings back into the string using joined(separator: “$”) function where each substring is joined by using “$”. And finally we display the output.

import Foundation
import Glibc
let StringVal = "Ball Pen color is Black"
print("Original String: ", StringVal)

// Converting string into an array of substrings
let arraySubstring =
StringVal.components(separatedBy:" ")

// Converting array of substring back in string where
// each whitespace character is replaced by %
let resString = arraySubstring.joined(separator: "%")
print("String after replacing spaces with \"%\":", resString) 

Output

Original String:  Ball Pen color is  Black
String after replacing spaces with "$": Ball$Pen$color$is$$Black

Method 5: Using the map() method

To replace the spaces of a string with a specific character we pass a closure in the map() method which checks if the character is a whitespace character or not. If the character is the whitespace character, then it replaces it with the specified character. If not then it keeps the original character. After that we use the String() initializer to convert back into the string.

Example

In the following Swift program, we will replace the space of a string with a specific character using map() method. So for that, we will apply map() method to each character in the given string. Inside the closure of map() function, it checks whether the current character is a whitespace character or not. If yes, then it replace the space(“ “) with “#” character. Otherwise keep the original character. After that we will convert the resultant array of characters back into the string using String() initializer and display the output.

import Foundation
import Glibc
let StringVal = "Meeta is cooking Paratha"
print("Original String: ", StringVal)
let resString = String(StringVal.map { $0 == " " ? "#": $0 })
print("String after replacing spaces with \"#\":",
resString) 

Output

Original String:  Meeta  is  cooking Paratha
String after replacing spaces with "#": Meeta##is##cooking#Paratha

Conclusion

So this is how we can replace the spaces of a string with a specific character. All the methods replace the spaces with the specified character. The user-defined method is good if the string is small, but if the string is large, then it takes more time to replace the string. So among all the methods the most efficient method is the replacingOccurrences() it takes less time as compared to other methods.

Updated on: 16-Jun-2023

612 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements