Trim Whitespace in a string in Swift

To trim starting and trailing whitespace characters in a string in Swift, you can use the trimmingCharacters() method of the String class instance.

For example, if inputStr is the given string, and we would to trim the whitespace character in this string, then use the following syntax.

inputStr.trimmingCharacters(in: .whitespacesAndNewlines)

whitespacesAndNewlines specified a set of whitespaces and new line unicode character.

The above specified method returns a new string created by trimming the whitespace characters from the edges of the calling string.

Examples

ADVERTISEMENT

1. Trimming whitespaces in the given string

In this example, we take a string value in inputStr, with whitespaces at the starting and at the ending of the string. We shall use trimmingCharacters() method and trim the given string. And then print the input string, and output string, to the output.

main.swift

import Foundation

let inputStr = "  hello world "
let outputStr = inputStr.trimmingCharacters(in: .whitespacesAndNewlines)

print("Input  string : \""+inputStr+"\"")
print("Output string : \""+outputStr+"\"")

Output

Conclusion

In this Swift Tutorial, we have seen how to trim the whitespace character from the edges of the String using trimmingCharacters() method.