Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Manipulation in Objective-C

Gotten a hold on how to fetch and write to variables in Objective-C, now it's time to learn how to do something more useful with them! Right now, I'm primarily trying to figure out how string manipulation works. In particular, I'm looking for the following functions:

  • Concatenation
  • Finding the length of a string (especially multi-byte/UTF-8 strings; I do a lot of work with East Asian languages)
  • Pulling just a portion of a string (e.g. the "foobar" out of "abcfoobarxyz")
  • Searching within a string (see the above example)
  • Changing case (upper, lower, title if it's simple to do)
  • Exploding/Imploding strings (e.g. creating and getting information from comma-separated lists)
  • Find/Replace within strings
  • Any other generally useful string functions that might be available
like image 556
Kaji Avatar asked Nov 22 '09 09:11

Kaji


1 Answers

Examples: Concatenation:

- (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

String Length:

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

Remove text from string:

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

Uppercase / Lowercase / Titlecase:

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

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

- (NSString*)titlecase:(NSString*)stringToTitleCase
{
   return [stringToTitleCase capitalizedString];
}

Find/Replace

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

I hope this helps!

PS: Don't forget to check the documentation, and Google is your friend. Good luck

like image 107
Alexandre Cassagne Avatar answered Sep 29 '22 13:09

Alexandre Cassagne