OneBite.Dev - Coding blog in a bite size

Trim A String In Swift

Code snippet for how to Trim A String In Swift with sample and detail explanation

String manipulation is a fundamental skill in programming. In Swift, you often need to trim unnecessary characters from a string, such as whitespaces or newlines.

Code snippet for Trimming a String in Swift

In the given example, we’ll demonstrate how you can trim a string in Swift.

let originalString = "   Hello, World!   "
let trimmedString = originalString.trimmingCharacters(in: .whitespacesAndNewlines)
print(trimmedString)  // "Hello, World!"

Code Explanation for Trimming a String in Swift

Let’s break this simple snippet down:

  1. let originalString = " Hello, World! ": Here we declare a constant originalString and assign it a string value that has leading and trailing spaces.

  2. let trimmedString = originalString.trimmingCharacters(in: .whitespacesAndNewlines): We declare another constant trimmedString. The trimmingCharacters(in: .whitespacesAndNewlines) function is called on originalString. This function is built into Swift’s String type and it removes specified set of characters from the beginning and the end of the string. In this case, it is removing whitespaces and newlines.

  3. print(trimmedString): Here we print the trimmedString to the console. You will notice that the string is printed without the leading and trailing whitespaces, hence “Hello, World!” is printed instead of ” Hello, World! “.

The end result of this code will be a string without any unnecessary characters at the beginning or end, improving the cleanliness and efficiency of your data handling. Whether you’re performing text comparisons, working with user input, or processing file data, knowing how to trim a string is a valuable tool in your Swift programming toolkit.

swift