Trim spaces from end of a NSString

Muszę usunąć spacje z końca łańcucha. Jak mogę to zrobić? Przykład: jeśli łańcuch jest "Hello " musi stać się "Hello"

Author: Damian Yerrick, 2011-04-22

14 answers

Use-stringbytrimmingcharactersinsset:

NSString *string = @" this text has spaces before and after ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];

(spowoduje to przycięcie białych znaków na obu końcach).

Swift 3

let string = " this text has spaces before and after "
let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
 863
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 13:38:39

Inne rozwiązanie polega na stworzeniu zmiennego ciągu znaków:

//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"
 18
Author: Matt H.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-19 07:03:02

Proszę...

- (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)];
}
Więc teraz po prostu zadzwoń. Przypuśćmy, że masz ciąg, który ma spacje z przodu i spacje na końcu i po prostu chcesz usunąć spacje na końcu, możesz go nazwać tak:
NSString *oneTwoThree = @"  TestString   ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];

resultString na końcu nie będzie spacji.

 11
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-12 23:06:02

Aby usunąć białe spacje tylko z początku i końca łańcucha w języku Swift:

Swift 3

string.trimmingCharacters(in: .whitespacesAndNewlines)

Poprzednie Wersje Swift

string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
 7
Author: lostAtSeaJoshua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-09 20:50:37

Swift version

Tylko przycinanie spacji na końcu łańcucha:

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

Spacje przycinające po obu stronach łańcucha:

var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
 3
Author: King-Wizard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-26 18:22:41

Spowoduje to usunięcie tylko wybranych znaków końcowych.

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
}
 3
Author: Teo Sartori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-04 19:08:56
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

Istnieje wiele innych zestawów znaków. Sprawdź sam, jak na swoje wymagania.

 3
Author: g212gs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-13 03:26:19

In Swift

Aby przyciąć spację i znak nowej linii z obu stron łańcucha:

var url: String = "\n   http://example.com/xyz.mp4   "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
 2
Author: Tina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-19 08:28:09

Proste rozwiązanie, aby przyciąć tylko jeden koniec zamiast obu końców w 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

I symetryczne narzędzie do przycinania tylko początku:

@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
 1
Author: Cœur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 04:08:49

Wymyśliłem tę funkcję, która w zasadzie zachowuje się podobnie do tej w odpowiedzi Alexa:

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

whitespaceCharacterSet oprócz spacji zawiera również znak tabulacji, który w moim przypadku nie mógł się pojawić. Więc myślę, że zwykłe porównanie może wystarczyć.

 0
Author: pckill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-13 11:49:56

Rozwiązanie jest opisane tutaj: Jak usunąć białe znaki z prawego końca NSString?

Dodaj następujące kategorie do 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]];
}

I używasz go jako takiego:

[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
 0
Author: Snouto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-16 05:35:26

Aby przyciąć wszystkie końcowe białe znaki (domyślam się, że jest to w rzeczywistości Twój zamiar), poniżej przedstawiamy dość przejrzysty i zwięzły sposób:

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

Jedna linijka, z końcówką regex.

 0
Author: PixelCloudSt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-11 19:29:23

Let string = "Test przycięty Ciąg"

Do usunięcia spacji i nowej linii użyj poniższego kodu :-

Let str_trimmed = yourString.trimmingCharacters(w: .whitespacesAndNewlines)

Do usuwania tylko spacji z łańcucha użyj poniższego kodu :-

Let str_trimmed = yourString.trimmingCharacters(w: .whitespaces)

 -1
Author: kangna sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-24 11:05:49
NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}
 -6
Author: Ashish Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-02 07:38:03