[objective-c] Remove all whitespaces from NSString

I've been trying to get rid of the white spaces in an NSString, but none of the methods I've tried worked.

I have "this is a test" and I want to get "thisisatest".

I've used whitespaceCharacterSet, which is supposed to eliminate the white spaces.

NSString *search = [searchbar.text stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

but I kept getting the same string with spaces. Any ideas?

This question is related to objective-c string cocoa nsstring

The answer is


stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end

Use

[YourString stringByTrimmingCharactersInSet:[NSCharacterSet  whitespaceAndNewlineCharacterSet]]

Use below marco and remove the space.

#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

in other file call TRIM :

    NSString *strEmail;
    strEmail = TRIM(@"     this is the test.");

May it will help you...


Easy task using stringByReplacingOccurrencesOfString

NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];

- (NSString *)removeWhitespaces {
  return [[self componentsSeparatedByCharactersInSet:
                    [NSCharacterSet whitespaceCharacterSet]]
      componentsJoinedByString:@""];
}

pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

I prefer using regex like this:

NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
                                     withString:@""
                                        options:NSRegularExpressionSearch
                                          range:NSMakeRange(0, [myStringlength])];
 //myNewString will be @"thisisatest"

You can make yourself a category on NSString to make life even easier:

- (NSString *) removeAllWhitespace
{
    return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
                                              options:NSRegularExpressionSearch
                                                range:NSMakeRange(0, [self length])];

}

Here is a unit test method on it too:

- (void) testRemoveAllWhitespace
{
    NSString *testResult = nil;

    NSArray *testStringsArray        = @[@""
                                         ,@"    "
                                         ,@"  basicTest    "
                                         ,@"  another Test \n"
                                         ,@"a b c d e f g"
                                         ,@"\n\tA\t\t \t \nB    \f  C \t  ,d,\ve   F\r\r\r"
                                         ,@"  landscape, portrait,     ,,,up_side-down   ;asdf;  lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & *  * ()+  +   "
                                         ];

    NSArray *expectedResultsArray   = @[@""
                                        ,@""
                                        ,@"basicTest"
                                        ,@"anotherTest"
                                        ,@"abcdefg"
                                        ,@"ABC,d,eF"
                                        ,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++"
                                        ];

    for (int i=0; i < [testStringsArray count]; i++)
    {
        testResult = [testStringsArray[i] removeAllWhitespace];
        STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
                     testStringsArray[i], expectedResultsArray[i], testResult);
    }
}

This for me is the best way SWIFT

        let myString = "  ciao   \n              ciao     "
        var finalString = myString as NSString

        for character in myString{
        if character == " "{

            finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")

        }else{
            finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")

        }

    }
     println(finalString)

and the result is : ciaociao

But the trick is this!

 extension String {

    var NoWhiteSpace : String {

    var miaStringa = self as NSString

    if miaStringa.containsString(" "){

      miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
        return miaStringa as String

    }
}

let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao

That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use

xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];

It will replace empty space with no space and empty field is taken care of by below method:

searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

I strongly suggest placing this somewhere in your project:

extension String {
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    func trim(withSet: NSCharacterSet) -> String {
        return self.stringByTrimmingCharactersInSet(withSet)
    }
}

This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.

NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];

When yourString was the current phone number.


Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to cocoa

How to update a single pod without touching other dependencies How to initialise a string from NSData in Swift Input from the keyboard in command line application Get current NSDate in timestamp format Xcode build failure "Undefined symbols for architecture x86_64" Cocoa Autolayout: content hugging vs content compression resistance priority setValue:forUndefinedKey: this class is not key value coding-compliant for the key iOS - Build fails with CocoaPods cannot find header files Get Current date & time with [NSDate date] Remove all whitespaces from NSString

Examples related to nsstring

NSRange to Range<String.Index> Creating NSData from NSString in Swift How do I check if a string contains another string in Swift? Converting NSString to NSDictionary / JSON convert NSDictionary to NSString How do I deserialize a JSON string into an NSDictionary? (For iOS 5+) How do I URL encode a string Objective-C and Swift URL encoding Convert an NSURL to an NSString Remove all whitespaces from NSString