Friday, December 19, 2008

iPhone Application Development: Objective-C / Cocoa: String Operations

Apple has provided a very nice implementation of the String class. Called NSString. Any string in Objective-C, written as @"Status" is represented in the code as an instance of NSString. Keep in mind that NSString objects are non-mutable. Just like Java String objects.

Go through NSString.h for many many more methods

NSString *nsStr = @"iPhone Development";
int len = [nsStr length]; //
Length of a string
NSString *result = [nsStr stringByAppendingString:anotherNsStr]; Combine 2 strings
NSRange range = [nsStr rangeOfString:@"iPhone"]; // range (not a pointer) would contain location and length of found string
NSString *str = [@"iPhone Application Development" substringFromIndex:7]; // -> Application Development
NSString *str = [@"iPhone Application Development" substringToIndex:6]; // -> iPhone
NSString *str = [@"iPhone Application Development" substringWithRange:NSMakeRange(7, 11)]; // -> Application

NSArray *arrayOfStrings = [@"iPhone Application Development" componentsSeparatedByString:@" "]; // split on space

// Converting between C Strings and NSStrings
NSString *nsStr = [[NSString alloc] initWithUTF8String:"iPhone"];
(const char *)cStr = [nsStr UTF8String];


Mutable Strings: If you need to make modifcations to NSString, use NSMutableString. Some of the valid messages to NSMutableString:


[msMuStr appendString:@" needs an iPhone"];
[msMuStr deleteCharactersInRange:NSMakeRange(7, 11)];
[msMuStr insertString:@" is a good application " atIndex:10];
[msMuStr replaceCharactersInRange:NSMakeRange(7, 11) withString:@" is a good application "];

5 comments:

  1. cool!!!
    very helpful!!!!

    can you write about Collections. Using of collection is very easy in C#, but in object C - not

    ReplyDelete
  2. Hi,

    Thanks for nice post. This may be very helpful to many iPhone Developers. You have given an example that is very nice to understand.

    ReplyDelete
  3. Thank you for sharing valuable information. Nice post. I enjoyed reading this post. The whole blog is very nice found some good stuff and good information here Thanks..Also visit my page wordpress development in delhi Android is a popular open source software usually used on hand-held devices and mobile phones.

    ReplyDelete
  4. Great Post Thanks

    For More Information You Can Visit This Website iPhone Application Development Solutions

    ReplyDelete
  5. mobile apps development Become Grooming business now you can avail services from everywhere in highly competitive world. However, iphone applications are designed few companies because these are more difficult and much more expensive.

    ReplyDelete