Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim spaces from end of a NSString

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"

like image 227
Andrea Mario Lufino Avatar asked Apr 22 '11 14:04

Andrea Mario Lufino


People also ask

How do you remove spaces from a string in Objective C?

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:@""] .

How do you remove trailing spaces in Swift?

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.

How do you trim a space in a string?

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.


2 Answers

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 } 
like image 121
Dan Avatar answered Oct 09 '22 17:10

Dan


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" 
like image 22
Matt H. Avatar answered Oct 09 '22 19:10

Matt H.