首页 > 白话Objective-C > 白话Objective-C之NSString

白话Objective-C之NSString

NSString,字符串处理类,下面整理了我做过的所有项目里面最常用到的API,并根据这些API写了相应的实例代码。
掌握了这些API,至少可以让你在处理NSString的时候,感觉到从容不迫。

 API:

实例代码:

//
//  main.m
//  NSString
//
//  Created by shenyixin on 13-8-31.
//  Copyright (c) 2013年 http://www.helloitworks.com/. All rights reserved.
//

#import 

int main(int argc, const char * argv[])
{
    
    @autoreleasepool {

        NSString *string;
        NSCharacterSet * characterSet;
        NSString *result;
        NSString *string1;
        NSString *string2;
        NSStringCompareOptions stringCompareOptions;
        NSComparisonResult compareResult;
        #pragma mark - Initializing Strings
        // - init
        string = [[NSString alloc] init];
        
        // - initWithString:
        string = [[NSString alloc] initWithString:@"hello string"];
        
        // - initWithFormat:
        string = [[NSString alloc] initWithFormat:@"hello %@ ",@"string"];
        
        #pragma mark - Initializing Strings Getting a String’s Length
        // – length
        NSInteger length = [string length];
        NSLog(@"length = %ld",length);
        
        #pragma mark - Getting Characters and Bytes
        // – characterAtIndex:
        unichar aChar = [string characterAtIndex:0];
        NSLog(@"%C",aChar);
        
        #pragma mark - Combining Strings
        
        // – stringByAppendingFormat:
        string = [string stringByAppendingFormat:@"hello %@ ",@"string"];
        
        // – stringByAppendingString:
        string = [string stringByAppendingFormat:@"hello string "];

        #pragma mark - Dividing Strings
        // – componentsSeparatedByString:
        /*
         the following code produces an array { @"Norman", @"Stanley", @"Fletcher" }.
         
         If list begins with a comma and space—for example, ", Norman, Stanley, Fletcher"—the array has these contents: { @"", @"Norman", @"Stanley", @"Fletcher" }
         
         If list has no separators—for example, "Norman"—the array contains the string itself, in this case { @"Norman" }.
         */
        NSString *list = @"Norman, Stanley, Fletcher";
        NSArray *listItems = [list componentsSeparatedByString:@", "];
        NSLog(@"%@",listItems);
        
        
        // - componentsSeparatedByCharactersInSet:
        //the following code split "A~B^C" to "A", "B" and "C"
        string = @"A~B^C";
        NSArray *array = [string componentsSeparatedByCharactersInSet:
                        [NSCharacterSet characterSetWithCharactersInString:@"^~"]];
        NSLog(@"%@", array);
        
        // – stringByTrimmingCharactersInSet:
        //  removes characters from the beginning and end of your string, not from any place in it
        string = @" hello it works \n";
        // remove whitespace and newline char
        NSString *strinbByTrimmingCharactersInSet = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSLog(@"strinbByTrimmingCharactersInSet %@",strinbByTrimmingCharactersInSet);
        
        
        // – substringToIndex:
        // – substringFromIndex:
        // – substringWithRange:
        /* 
        substringToIndex:  [0,index)
        substringFromIndex: [index,end]
        substringWithRange: [range.index,rang.index+rang.length)
         */
        string = @"helloitworks";
        NSString *substringToIndex = [string substringToIndex:5];
        NSLog(@"substringToIndex = %@",substringToIndex);
        NSString *substringFromIndex = [string substringFromIndex:5];
        NSLog(@"substringFromIndex = %@",substringFromIndex);
        NSString *substringWithRange = [string substringWithRange:NSMakeRange(0, 5)];
        NSLog(@"substringWithRange = %@",substringWithRange);

        #pragma mark - Finding Characters and Substrings
        // – rangeOfCharacterFromSet:
        //the range in the receiver of the first character found from aSet. Returns a range of {NSNotFound, 0} if none of the characters in aSet are found.
        string = @"hello it works";
        characterSet = [NSCharacterSet characterSetWithCharactersInString:@"it"];
        NSRange rangeOfCharacterFromSet = [string rangeOfCharacterFromSet:characterSet];
        if (rangeOfCharacterFromSet.location != NSNotFound) {
            NSLog(@"rangeOfCharacterFromSet location = %lu, length = %lu",rangeOfCharacterFromSet.location,rangeOfCharacterFromSet.length);
        } else {
            NSLog(@"rangeOfCharacterFromSet not found!");
        }
        
        // - rangeOfString:
        string = @"hello it works";
        NSRange rangeOfString = [string rangeOfString:@"it"];
        if (rangeOfString.location != NSNotFound) {
            NSLog(@"rangeOfString location = %lu, length = %lu",rangeOfCharacterFromSet.location,rangeOfCharacterFromSet.length);
        } else {
            NSLog(@"rangeOfString not found!");
        }

        
        #pragma mark - Replacing Substrings
        // – stringByReplacingOccurrencesOfString:withString:
        
        string = @"hello it works";
        result = [string stringByReplacingOccurrencesOfString:@"it works" withString:@"world"];
        NSLog(@"stringByReplacingOccurrencesOfString result = %@",result);
        

        #pragma mark - Identifying and Comparing Strings
        // – isEqualToString:
        string1 = @"hello string";
        string2 = @"hello it works";
        
        if ([string1 isEqualToString:string2] == YES) {
            NSLog (@"string1 == string2");
        }
        else {
            NSLog (@"string1 != string2");
        }
        
        // – hasPrefix:
        string = @"hello it works";
        if ([string hasPrefix:@"hello"]) {
            NSLog(@"%@ hasPrefix %@",string,@"hello");
        } else {
            NSLog(@"%@ do not hasPrefix %@",string,@"hello");
        }
        
        // – hasSuffix:
        string = @"hello it works";
        if ([string hasSuffix:@"hello"]) {
            NSLog(@"%@ hasSuffix %@",string,@"hello");
        } else {
            NSLog(@"%@ do not hasSuffix %@",string,@"hello");
        }
                
        // – compare:
        compareResult = [string1 compare:string2];
        if (compareResult == NSOrderedAscending)
            NSLog (@"string1 < string2");
        else if (compareResult == NSOrderedSame)
            NSLog (@"string1 == string2");
        else // must be NSOrderedDescending NSLog (@"str1 > str2");
            NSLog (@"str1 > str2");
        
        // - caseInsensitiveCompare:
        compareResult = [string1 caseInsensitiveCompare:string2];
        if (compareResult == NSOrderedAscending)
            NSLog (@"string1 < string2");
        else if (compareResult == NSOrderedSame)
            NSLog (@"string1 == string2");
        else // must be NSOrderedDescending NSLog (@"str1 > str2");
            NSLog (@"str1 > str2");
        
        // – compare:options:
        stringCompareOptions = NSCaseInsensitiveSearch;
        compareResult = [string1 compare:string2 options:stringCompareOptions];
        if (compareResult == NSOrderedAscending)
            NSLog (@"string1 < string2");
        else if (compareResult == NSOrderedSame)
            NSLog (@"string1 == string2");
        else // must be NSOrderedDescending NSLog (@"str1 > str2");
            NSLog (@"str1 > str2");
        
        
        #pragma mark - Changing Case
        // – capitalizedString
        string = @"hello it works";
        NSString *capitalizedString = [string capitalizedString];
        NSLog (@"CapitalizedString conversion: %@",capitalizedString);
        
        // - uppercaseString
        // Convert a string to uppercase
        string = @"hello it works";
        NSString *uppercaseString = [string uppercaseString];
        NSLog (@"Uppercase conversion: %@",uppercaseString);
        // - lowercaseString
        // Convert a string to lowercase
        string = @"HELLO IT WORKS";
        NSString *lowercaseString = [string lowercaseString];
        NSLog (@"Lowercase conversion: %@", lowercaseString);
        
        #pragma mark - Getting Numeric Values
        //todo
        
        #pragma mark - You can convert between C string and NSString:
        const char *cString = "Blah blah";
        NSString *nsString;
        // Create an NSString from a C string
        nsString = [NSString stringWithUTF8String:cString];
        // Create a C string from an NSString 
        cString = [nsString UTF8String];
        
    }
    return 0;
}


Refer:

NSString Class Reference

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

String Programming Guide

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/introStrings.html

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.