Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove extra empty space in NSString?

is there a simple way to remove the extra spaces in a string? ie like...

NSString *str = @"this string has extra              empty spaces";

result should be:

NSString *str = @"this string has extra empty spaces";

Thanks!

like image 638
Unikorn Avatar asked Oct 06 '10 07:10

Unikorn


People also ask

How do I remove spaces from QString?

[ QString::simplified ] Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space. Once the string is simplified, the white spaces can easily be removed. Option 2: Use a QRegExp to capture all types of white space in remove .

How do I remove a space in Swift?

To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered.

How do I trim 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:@""] .

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


1 Answers

replace all double space with a single space until there are no more double spaces in your string.

- (NSString *)stripDoubleSpaceFrom:(NSString *)str {
    while ([str rangeOfString:@"  "].location != NSNotFound) {
        str = [str stringByReplacingOccurrencesOfString:@"  " withString:@" "];
    }
    return str;
}
like image 149
Matthias Bauch Avatar answered Sep 27 '22 18:09

Matthias Bauch