[nsstring] 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"

This question is related to nsstring whitespace trim

The answer is


The solution is described here: How to remove whitespace from right end of NSString?

Add the following categories to NSString:

- (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
}

- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
    return [self stringByTrimmingTrailingCharactersInSet:
            [NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

And you use it as such:

[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]

Here you go...

- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
    NSUInteger location = 0;
    unichar charBuffer[[strtoremove length]];
    [strtoremove getCharacters:charBuffer];
    int i = 0;
    for(i = [strtoremove length]; i >0; i--) {
        NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
        if(![charSet characterIsMember:charBuffer[i - 1]]) {
            break;
        }
    }
    return [strtoremove substringWithRange:NSMakeRange(location, i  - location)];
}

So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:

NSString *oneTwoThree = @"  TestString   ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];

resultString will then have no spaces at the end.


NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceAndNewlineCharacterSet]];
//for remove whitespace and new line character

NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet punctuationCharacterSet]]; 
//for remove characters in punctuation category

There are many other CharacterSets. Check it yourself as per your requirement.


To remove whitespace from only the beginning and end of a string in Swift:

Swift 3

string.trimmingCharacters(in: .whitespacesAndNewlines)

Previous Swift Versions

string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))

let string = " Test Trimmed String "

For Removing white Space and New line use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)

For Removing only Spaces from string use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)


Swift version

Only trims spaces at the end of the String:

private func removingSpacesAtTheEndOfAString(var str: String) -> String {
    var i: Int = countElements(str) - 1, j: Int = i

    while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
        --i
    }

    return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}

Trims spaces on both sides of the String:

var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

I came up with this function, which basically behaves similarly to one in the answer by Alex:

-(NSString*)trimLastSpace:(NSString*)str{
    int i = str.length - 1;
    for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
    return [str substringToIndex:i + 1];
}

whitespaceCharacterSet besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.


A simple solution to only trim one end instead of both ends in Objective-C:

@implementation NSString (category)

/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger i = self.length;
    while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
        i--;
    }
    return [self substringToIndex:i];
}

@end

And a symmetrical utility for trimming the beginning only:

@implementation NSString (category)

/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
    NSUInteger i = 0;
    while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
        i++;
    }
    return [self substringFromIndex:i];
}

@end

To trim all trailing whitespace characters (I'm guessing that is actually your intent), the following is a pretty clean & concise way to do it.

Swift 5:

let trimmedString = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)

Objective-C:

NSString *trimmedString = [string stringByReplacingOccurrencesOfString:@"\\s+$" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];

One line, with a dash of regex.


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"

NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

This will remove only the trailing characters of your choice.

func trimRight(theString: String, charSet: NSCharacterSet) -> String {

    var newString = theString

    while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
        newString = String(newString.characters.dropLast())
    }

    return newString
}

In Swift

To trim space & newline from both side of the String:

var url: String = "\n   http://example.com/xyz.mp4   "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())