有一篇文章寫了:iOS開發之NSString的幾條實用技巧 , 今天這篇,我們講講NSString的八條實用技巧。大家可以收藏起來,方便開發隨時可以複製貼上。
0.首字母大寫
程式碼:
//首字母大寫
NSString *string = @"ligang";
NSLog(@"string: %@",[string capitalizedString]);
列印:
2015-07-16 23:06:11.652 iOSStrongDemo[10279:3062010] string: Ligang
1.分割字串
程式碼:
//分割字串
NSString *string = @"This is a iOSDevTip";
NSArray *array = [string componentsSeparatedByString:@"a"];
NSString *string1 = [array objectAtIndex:0];
NSString *string2 = [array objectAtIndex:1];
NSLog(@"string1:%@ string2:%@",string1,string2);
列印:
2015-07-16 22:40:39.559 iOSStrongDemo[10165:3055448] string1:This is string2: iOSDevTip
2.追加字串
程式碼:
//追加字串
NSMutableString *string = [[NSMutableString alloc] initWithString:@"I Love "];
[string appendString:@"China"];
NSLog(@"string:%@",string);
列印:
2015-07-16 22:42:32.305 iOSStrongDemo[10189:3056410] string:I Love China
3.插入字串
程式碼:
//插入字串
NSMutableString *string = [[NSMutableString alloc] initWithString:@"I China"];
[string insertString:@"Love " atIndex:2];
NSLog(@"string: %@",string);
列印:
2015-07-16 22:44:10.706 iOSStrongDemo[10206:3057014] string: I Love China
4.刪除字串
程式碼:
//刪除字串
NSMutableString *string = [[NSMutableString alloc] initWithString:@"I love China"];
[string deleteCharactersInRange:NSMakeRange(2, 4)];
NSLog(@"String1: %@",string);
列印:
2015-07-16 22:46:58.437 iOSStrongDemo[10219:3057749] String1: I China
5.判斷是否包含前字尾
程式碼:
//判斷是否包含前字尾
NSString *string = @"I love China";
BOOL isHasI = [string hasPrefix:@"I"];
BOOL isHasChina = [string hasSuffix:@"China"];
6.替換字串
程式碼:
//替換字串
NSString *string = @"I love China";
NSString *replaceString = [string stringByReplacingOccurrencesOfString:@"love" withString:@"like"];
NSLog(@"replaceString: %@",replaceString);
列印:
2015-07-16 22:56:07.405 iOSStrongDemo[10236:3059503] replaceString: I like China
7.去除字串首尾的空格和換行符
程式碼:
//去除字串首尾的空格和換行符
NSString *string = @" I love China ";
NSString *text = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"text:%@",text);
列印:
2015-07-16 23:00:47.845 iOSStrongDemo[10265:3061013] text:I love China
程式碼已經更新,demo下載地址:iOSStrongDemo