I need to remove spaces from the end of a string. How can I do that? Example: if string is "Hello "
it must become "Hello"
stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle. For those who are trying to remove space in the middle of a string, use [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] .
To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
Taken from this answer here: https://stackoverflow.com/a/5691567/251012
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet { NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet] options:NSBackwardsSearch]; if (rangeOfLastWantedCharacter.location == NSNotFound) { return @""; } return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive }
Another solution involves creating mutable string:
//make mutable string NSMutableString *stringToTrim = [@" i needz trim " mutableCopy]; //pass it by reference to CFStringTrimSpace CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim); //stringToTrim is now "i needz trim"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With