C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
NSCharacterSet: We create a NSCharacterSet with three characters—a space, period, and a question mark.
Next: We invoke the trim method, stringByTrimmingCharactersInSet. We pass the set instance as an argument.
Result: The string returned has no leading or trailing spaces (and no period). The endIndex values indicate 3 characters were removed.
Swift program that trims string
import Foundation
// The string we are trimming.
let source = " Areopagitica, John Milton. "
// Create a character set of chars to trim.
let set = NSCharacterSet(charactersInString: " .?")
// Call func with character set.
let result = source.stringByTrimmingCharactersInSet(set)
// Write the result.
print(result)
// Print before and after lengths.
print(source.endIndex)
print(result.endIndex)
Output
Areopagitica, John Milton
28
25
Then: We take a substring (of the inner part of the string) to perform the trimming operation.
Substring