2012年11月24日 星期六

NSString 物件的操作方法

宣告與格式化
//建立字串物件
NSString *str = @"NSString";
//建立空字串
NSString *str =[[NSString alloc] init];
//與CString的轉換
char *cstring = "CString";
NSString *str = [[NSString alloc] initWithCString:cstring];
//字串格重新式化
NSString *str =[[NSString alloc] initWithString:@"NSString"];
str = [NSString stringWithFormat:@"This is %@", str];
NSLog(@"%@", str);


大小寫的轉換
//字串的大小寫轉換
NSString *str =[[NSString alloc] initWithString:@"NSString"];
//全部大寫
NSLog(@"%@",[str uppercaseString]);
//全部小寫
NSLog(@"%@",[str lowercaseString]);
//字首大寫
NSLog(@"%@", [str capitalizedString]);


在 iOS 6 SDK 中使用新的方法函式加入了 NSLocale 的概念,使裝置在不同的語系設定下皆可以正確的轉換這些字串。
//全部大寫
NSString *upperString = [string uppercaseStringWithLocale:[NSLocale currentLocale]];
NSLog(@"全部大寫: %@", upperString);
//全部小寫
NSString *lowerString = [string lowercaseStringWithLocale:[NSLocale currentLocale]];
NSLog(@"全部小寫: %@", lowerString);
//只有字首大寫
NSString *capString = [string capitalizedStringWithLocale:[NSLocale currentLocale]];
NSLog(@"只有字首大寫: %@", capString)


比較
//字串比較
NSString *str_A =[[NSString alloc] initWithString:@"NSString"];
NSString *str_B =[[NSString alloc] initWithString:@"nsstring"];
BOOL compare;

//字串區分大小寫比較
compare = [str_A isEqualToString:str_B];

//字串不區分大小寫比較
compare = [str_A caseInsensitiveCompare:str_B] == NSOrderedSame;


排序

NSString *string = @"0";
NSComparisonResult result = [string caseInsensitiveCompare:@"A"];

switch (result) {
case NSOrderedAscending:
NSLog(@"升冪");
break;

case NSOrderedSame:
NSLog(@"忽略大小寫相同的字串");
break;

case NSOrderedDescending:
NSLog(@"降冪");
break;

default:
NSLog(@"無法判定");
break;
}

在 Objective-C 中 NSComparisonResult 的定義。
enum _NSComparisonResult {NSOrderedAscending = -1, NSOrderedSame, NSOrderedDescending};
typedef NSInteger NSComparisonResult;


搜尋
//搜尋字串
NSString *str =[[NSString alloc] initWithString:@"NSString"];
//有區分大小寫
NSRange search = [str rangeOfString:@"Str"];
//數字表示第幾字元開始有符合(從0開始)
NSLog(@"%i", search.location);


擷取
//字串擷取
NSString *str =[[NSString alloc] initWithString:@"NSString"];

//擷取前五位元
NSLog(@"%@", [str substringToIndex:5]);

//擷取時略過前五位元
NSLog(@"%@", [str substringFromIndex:5]);

//從第二個位元開始擷取三個位元(第一個字符為第零位元)
NSLog(@"%@", [str substringWithRange:NSMakeRange(2, 3)]);


替換
//字串替換
NSString *str =[[NSString alloc] initWithString:@"NSString"];
NSString *_str;

//尋找字串並取代
_str = [str stringByReplacingOccurrencesOfString:@"NS" withString:@"CS"];
NSLog(@"%@", _str);

//尋找範圍並取代
_str = [str stringByReplacingCharactersInRange:NSMakeRange(2, 3) withString:@"*******"];
NSLog(@"%@", _str);


如何拆解 NSString 並置入 NSArray 中。
NSString *string = @"Never Forget Me";
//字串以空白間鍵做分段依據
NSArray *strArray = [string componentsSeparatedByString:@" "];

沒有留言:

張貼留言