372

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"

Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64
Andrea Mario Lufino
  • 7,921
  • 12
  • 47
  • 78
  • 1
    There is a Swift version of it.http://stackoverflow.com/questions/26797739/does-swift-has-trim-method-on-string – tounaobun Jan 18 '16 at 08:40

14 Answers14

903

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
}
JoeCortopassi
  • 5,083
  • 7
  • 37
  • 65
Dan
  • 17,375
  • 3
  • 36
  • 39
  • 157
    To include newlines in the set of characters, use `whitespaceAndNewlineCharacterSet`. – penfold Nov 22 '11 at 12:45
  • 9
    Just a little note: this method removes the white spaces from both ends. It does not remove white spaces from the inside of the string. – Alex Jun 24 '14 at 14:40
  • 10
    I don't understand how not answering the question gets so many upvotes. Your solution removes whitespace at the beginning of the string as well, and that's not what was asked for. – James Boutcher Oct 27 '15 at 13:34
  • 5
    @JamesBoutcher the reason that it gets so many upvotes is that we got here looking for "trim NSString" in Google and this is the right answer for that question. It's true that the OP asked for something else. – Dan Rosenstark Nov 19 '15 at 00:31
  • To concern Emoji, the last line should be `return [self substringToIndex:rangeOfLastWantedCharacter.location + rangeOfLastWantedCharacter.length];` – vinsent Mar 24 '23 at 03:48
21

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"
Pang
  • 9,564
  • 146
  • 81
  • 122
Matt H.
  • 10,438
  • 9
  • 45
  • 62
13

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.

Sandy Chapman
  • 11,133
  • 3
  • 58
  • 67
Alex
  • 181
  • 2
  • 10
11
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.

Pang
  • 9,564
  • 146
  • 81
  • 122
g212gs
  • 863
  • 10
  • 26
9

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()))
lostAtSeaJoshua
  • 1,695
  • 2
  • 21
  • 34
  • 1
    Isn't this going to trim ALL whitespace and newline characters? the question asks how to trim from the end. – Giorgos Ath Dec 21 '16 at 10:22
  • @GiorgosAth No this is only going to trim the characters from the beginning or end of string. From the apple documentation for `stringByTrimmigCharactersInSet:` - "Returns a new string made by removing from both ends of the receiver characters contained in a given character set." https://developer.apple.com/reference/foundation/nsstring/1415462-stringbytrimmingcharactersinset?language=objc – lostAtSeaJoshua Jan 09 '17 at 16:32
  • @GiorgosAth also this is the same exact code as the accepted answer just in Swift. – lostAtSeaJoshua Jan 09 '17 at 20:49
  • The question was about removing from the end. This answer removes from beginning and end. Therefore this is not a valid answer. – Patrick Apr 02 '20 at 03:33
4

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())
King-Wizard
  • 15,628
  • 6
  • 82
  • 76
4

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
}
Teo Sartori
  • 1,082
  • 14
  • 24
3

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())
Tina
  • 312
  • 3
  • 5
3

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
3

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.

PixelCloudSt
  • 2,805
  • 1
  • 18
  • 19
1

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]
Cœur
  • 37,241
  • 25
  • 195
  • 267
Snouto
  • 1,039
  • 1
  • 7
  • 21
0

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.

pckill
  • 3,709
  • 36
  • 48
-1

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)

-7
NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
Ashish Patel
  • 332
  • 2
  • 7