1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

NSString and NSRange Tutorials

Discussion in 'iPhone/iPad Programming' started by nashyo, Aug 24, 2012.

  1. macrumors 6502

    nashyo

    #1
    Does anyone have any good hands on tutorials for learning more about the power of the NSString and NSRange classes please?

    I want to become much more familiar with their use. There are a lot of methods in these classes and the only real way to remember what power they have, is to use them.

    Thanks
     
  2. macrumors member

    #2
    If you simply want to learn what methods they have and what they do, the apple documentation is an excellent way to familiarize yourself with them (BTW, NSRange is NOT a class and therefore does not have methods)

    NSString
    NSRange

    As for tutorials, I don't think they are necessary. If you were trying to learn something complicated then I would say tutorials are great. But NSStrings and NSRange aren't complicated. An NSRange is a struct that has just two integers, a location and length. That's it.
    And NSStrings are often just used for displaying text and providing keys for dictionarys and such. The only methods that you will end up using a lot are stringWithFormat: and possibly stringByAppendingString: Of course there are others but I find that they aren't needed as often.
     
  3. macrumors 6502a

    Duncan C

    #3
    As you say, the way to learn about them is to USE them, not to read about them. Reading a tutorial is reading about them, not using them.

    Set yourself some tasks and write code that accomplishes those tasks.

    here's a project for you.

    Create your own version of stringByReplacingOccurrencesOfString:withString:.

    Write it using a while loop and rangeOfString to find each occurrence of the string you are replacing, and stringByReplacingCharactersInRange:withString: to create a new string. In each pass through the while loop, replace your working string with a newly created string.

    (This is an inefficient way to do it, but it is a good learning exercise.)
     
  4. solderguy1, Aug 24, 2012
    Last edited: Aug 24, 2012

    macrumors member

    #4
    Here's my NSString notes, regular style and mutable to help you get started. I like writing note files for each language and platform I use. Great for studying and cut-and-pastes. If it's not in there, a quick google search will usually find an example. Then I verify it in code and add it into the notes for next time.

    The official Apple/Google/whatever docs are kinda dull. A feisty debate on Stack Overflow makes learning more fun.

    Also it's good to keep in mind that NSMutableString can use most of NSString's methods because it is a subclass. NSArray/NSMutableArray as well as UIView/UIControl also have this relationship.


    Code:
    ********************************************************************************************************
    *                                                                                                      *
    *                                  *String *NSString *NSMutableString                                  *
    *                                                                                                      *
    ********************************************************************************************************
    * *
    
    C-style string
      "Programming is fun"
      Composed of 8-bit chars
    
    NSString object
      Composed of 16-bit unichars
      	@"Programming is fun"
    
      %@  = argument to print NSString class and subclass objects
    		NSString *str = @"This is a test";
    		NSLog (@"%@", str);
    
    EVEN MORE METHODS in obj-C book page 326
    
    NSScanner
      Take a look at this class if you need to parse strings into tokens
    
    NSString Operations
      Uses immutable strings that cannot be changed
      Methods are actually creating an entirely new string
      More than 100 methods available
      They do take a sizable memory if you use too many
     
     Declaring
    			NSString *str1 = @"This is string A";
    			NSString *str2 = @"This is string B";
    			NSString *res;
    
     Declaring with arguments
     	NSString *query = [NSString stringWithFormat:@"SELECT * FROM user WHERE id = %d", questionNum];
    
    
     Char count
    			NSLog (@"Length of str1: %lu", [str1 length]);
    
     Copy string
    			res = [NSString stringWithString: str1];
    
     Append onto string
    			str2 = [str1 stringByAppendingString: str2];
    
     Substring
        			NSString *firstLetter = [answer.text substringToIndex:1];
    			NSLog([@"1234567890" substringFromIndex:4]);			//567890
    			NSLog([@"1234567890" substringToIndex:6]);			//123456
    			NSLog([@"1234567890" substringWithRange:NSMakeRange(3, 5)]);	//45678
    
     Equality test
    			if ([str1 isEqualToString: res] == YES) {
    			// str1 = res simple creates new reference to same object in memory
                		if ([firstLetter isEqualToString: @"A"]) 
    
    
     Test if string is <,>,==
    			NSComparisonResult compareResult;
    			compareResult = [str1 compare: str2];
    			if (compareResult == NSOrderedAscending)  //NSOrderdSame, NSOrderedDescending
    
     Convert to uppercase
    			res = [str1 uppercaseString];  //lowercaseString
    
     Convert C string to NSString
    			[NSString stringWithUTF8String:buf]
     
    NSMutableString
      Designed to have characters inside them changed
      Some initWithCapacity methods
    			
    			NSMutableString *mstr;
    
      Create mutable string from non mutable
    			mstr = [NSMutableString stringWithString: str1];
    
      Insert characters
    			[mstr insertString: @" mutable" atIndex: 7];
    
      Concatenation (insert at end)
    			[mstr insertString: @" and string B" atIndex: [mstr length]];
    
      Set directly
    			[mstr setString: @"This is string A"];
    
      Append directly
    			[mstr appendString: @" and string C"];
    
      Delete substring based on range
    			[mstr deleteCharactersInRange: NSMakeRange (16,13)];
    
      Find range first and then use it for deletion
    			NSRange substr = [mstr rangeOfString: @"string B and "];
    			if (substr.location != NSNotFound) {
    			    [mstr deleteCharactersInRange: substr];
    			    NSLog (@"%@", mstr);
    			}
    
      Replace a ranch of characters with another
    			[mstr replaceCharactersInRAnge: NSMakeRange(8, 8)
    					withString: @"a mutable string"];
    
      Search and replace
    			NSString *search = @"This is";
    			NSString *replace = @"An example of";
    
    			substr = [mstr rangeOfString: search];
    			if (substr.location != NSNotFound) {
    				[mstr replaceCharactersInRange: substr
    						    withString: replace];
    			}
    
      Search and replace all occurrences
    			search = @"a";
    			replace = @"X";
    
    			substr = [mstr rangeOfString: search];
    
    			while (substr.location != NSNotFound) {
    				[mstr replaceCharactersInRange: substr
    						    withString: replace];
    				  substr = [mstr rangeOfString: search];
    			}
    
    Easy replacement (haven't verified)
    //    [mstr setString:@""];
    //    [mstr appendFormat: @" made longer %@.", @"with formating"];
    
     

Share This Page