Trim spaces from end of a NSString

NsstringWhitespaceTrim

Nsstring Problem Overview


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"

Nsstring Solutions


Solution 1 - Nsstring

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
}

Solution 2 - Nsstring

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"

Solution 3 - Nsstring

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.

Solution 4 - Nsstring

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.

Solution 5 - Nsstring

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

Solution 6 - Nsstring

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

Solution 7 - Nsstring

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
}

Solution 8 - Nsstring

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

Solution 9 - Nsstring

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

Solution 10 - Nsstring

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.

Solution 11 - Nsstring

The solution is described here: https://stackoverflow.com/questions/5689288/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]

Solution 12 - Nsstring

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.

Solution 13 - Nsstring

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)

Solution 14 - Nsstring

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrea Mario LufinoView Question on Stackoverflow
Solution 1 - NsstringDanView Answer on Stackoverflow
Solution 2 - NsstringMatt H.View Answer on Stackoverflow
Solution 3 - NsstringAlexView Answer on Stackoverflow
Solution 4 - Nsstringg212gsView Answer on Stackoverflow
Solution 5 - NsstringlostAtSeaJoshuaView Answer on Stackoverflow
Solution 6 - NsstringKing-WizardView Answer on Stackoverflow
Solution 7 - NsstringTeo SartoriView Answer on Stackoverflow
Solution 8 - NsstringTinaView Answer on Stackoverflow
Solution 9 - NsstringCœurView Answer on Stackoverflow
Solution 10 - NsstringPixelCloudStView Answer on Stackoverflow
Solution 11 - NsstringSnoutoView Answer on Stackoverflow
Solution 12 - NsstringpckillView Answer on Stackoverflow
Solution 13 - Nsstringkangna sharmaView Answer on Stackoverflow
Solution 14 - NsstringAshish PatelView Answer on Stackoverflow