Remove leading whitespaces from a string in Swift

This tutorial will see how to remove the leading whitespaces from a string in Swift. The spaces at the beginning of the string only should be removed others should be kept the same. This is also called the ‘trimming’ of string.

Steps to be followed to remove leading whitespaces

Step 1: Define the string which you want to trim.

Step 2: Define another empty string named filtered. Define the variableisLeading of Boolean type and set the value to true.

Step 3: Now iterate through the characters of the string using for loop. for the character if the value of isLeading is true and it’s whitespace then continue in the loop.

  • isWhitespace: It returns a Boolean value whether the character is whitespace or not.
  • continue: It is the keyword that specifies the loop will continue. It is used generally when you want to continue the loop without executing any statement.

Step 4: else make the value of isLeading equal to false because this character will not be the leading character. And append the character in the filtered string.

  • String(element): It is a method that converts the data type of an element to string.

Step 5: Print the filtered string which is trimmed now.

Swift Code:

Here is the Swift code for removing the leading whitespaces from the string.

var str = "   Hello  there"
var filtered = ""
var isLeading = true
for character in str {
    if character.isWhitespace && isLeading {
        continue
    }
    else {
        isLeading = false
        filtered = filtered + String(character)
    }
}
print(filtered)

Output:

Hello  there

Also, refer to Get the nth character of a string in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *