Friday, April 27, 2012

Remove character from NSString in iPhone programming?


NSString *myString = @"A B C D E F G";



I want to remove the spaces, and get a string out like "ABCDEFG".



Please help me...



Thanks and regards


Source: Tips4all

3 comments:

  1. You could use:

    NSString *stringWithoutSpaces = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];

    ReplyDelete
  2. If you want to support more than one space at a time, or support any whitespace, you can do this:

    NSString * noSpaces = [[myString componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];

    ReplyDelete
  3. Taken from NSString

    stringByReplacingOccurrencesOfString:withString:


    Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

    - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement


    Parameters

    target

    The string to replace.


    replacement

    The string with which to replace target.


    Return Value

    A new string in which all occurrences of target in the receiver are replaced by replacement.

    ReplyDelete