String manipulation in iPhone applications

These examples of string manipulation in iPhone apps were taken from the Internet and I don’ pretend on the authority rights for them.

  1. Appending string to another string:

    NSString *myString = @"This";
    NSString *test = [myString stringByAppendingString:@" is just a test"];

  2. Method with wide possibilities to format string and concatenate several strings:

    - (NSString*) concatenateString:(NSString*)stringA withString:(NSString*)stringB {
    NSString *finalString = [NSString stringWithFormat:@"%@%@", stringA, stringB]; return finalString; }



    The advantage of this method is that it is simple to put text between the two strings (e.g. Put a “-” replace %@%@ by %@ – %@ and that will put a dash between stringA and stringB

  3. String Length:

    - (int) stringLength:(NSString*)string { return [string length]; //Not sure for east-asian languages, but works fine usually }

  4. Remove text from string:

    - (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input { return [input stringByReplacingOccurrencesOfString:textToRemove withString:@""]; }

  5. Uppercase / Lowercase / Titlecase:

    - (NSString*)uppercase:(NSString*)stringToUppercase { return [stringToUppercase upercaseString]; }

    - (NSString*)lowercase:(NSString*)stringToLowercase { return [stringToUppercase lowercaseString]; }


  6. Find/Replace:

    - (NSString*)findInString:(NSString*)string replaceWithString:(NSString*)stringToReplaceWith { return [input stringByReplacingOccurrencesOfString:string withString:stringToReplaceWith]; }

  7. String comparison Case Sensitive:

    if ([category isEqualToString:@"Some String"])
    {
    doSomething = YES;
    }



    Case Insensitive:

    if (!([category compare:@"Some String" options:NSCaseInsensitiveSearch]))
    {
    doSomething = YES;
    }



References:

  1. http://stackoverflow.com/questions/1778227/string-manipulation-in-objective-c
  2. http://www.techotopia.com/index.php/Working_with_String_Objects_in_Objective-C – The best reference on this topic

Leave a Reply

Your email address will not be published. Required fields are marked *