一、用字符将NSArray中的元素拼接起来
1
NSArray *array = [NSArray arrayWithObjects:@
"hello"
,@
"world"
,nil];
2
3
4
NSString *string = [array componentsJoinedByString:@
" "
];
5
6
NSLog(@
"string = %@"
,string);
打印结果:hello world
二、截取子串:这里以获取时间为例,利用NSDate获取到当前时间时,有时候只需要日期或者只需要时间
①从字符串开头截取到指定的位置,如
01
02
NSDate *date = [NSDate date];
03
04
05
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
06
07
08
[dateformatter setDateFormat:@
"YYYY-MM-dd HH:mm"
];
09
10
11
NSString *string = [dateformatter stringFromDate:date];
12
NSLog(@
"\ncurrent = %@"
,string);
13
14
15
NSString *currentDate = [string substringToIndex:10];
16
17
NSLog(@
"\ncurrentDate = %@"
,currentDate);
打印结果:
current = 2013-06-27 11:12
currentDate = 2013-06-27
②抽取中间子串-substringWithRange
1
2
NSString *currentMonthAndDate = [string substringWithRange:[NSMakeRange(5, 5)]];
3
4
NSLog(@
"currentMonthAndDate = %@"
,currentMonthAndDate);
打印结果:
currentMonthAndDate = 06-27
③从某一位置开始截取-
substringFromIndex
1
2
NSString *currentTime = [string substringFromIndex:11];
3
4
NSLog(@
"\ncurrentTime = %@"
,currentTime);
打印结果:
currentTime = 11:25
三、比较字符串
1
NSString *first = @
"string"
;
2
NSString *second = @
"String"
;
①判断两个字符串是否相同-isEqualToString方法1
BOOL
isEqual = [first isEqualToString:second];
2
3
NSLog(@
"first is Equal to second:%@"
,isEqual);
打印结果:
first is Equal to second:0
②compare方法比较字符串
三个值
1
NSOrderedSame
2
NSOrderedAscending
3
NSOrderedDescending
1
BOOL
result = [first compare:sencond] == NSOrderedSame;
2
NSLog(@
"result:%d"
,result);
打印结果:
result:0
1
BOOL
result = [first compare:second] == NSOrderedAscending;
2
NSLog(@
"result:%d"
,result);
打印结果:
result:0
1
<b><b>
BOOL
result = [first compare:second] == NSOrderedDecending; NSLog(@
"result:%d"
,result);</b></b>
打印结果:result:1
③不考虑大小写比较字符串
1
BOOL
result = [first compare:second
2
options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame;
3
NSLog(@
"result:%d"
,result);
打印结果:
result:1
四、改变字符串大小写
1
NSString *aString = @
"A String"
;
2
NSString *string = @
"String"
;
3
4
NSLog(@
"aString:%@"
,[aString uppercaseString]);
5
6
NSLog(@
"string:%@"
,[string lowercaseString]);
7
8
NSLog(@
"string:%@"
,[string capitalizedString]);
打印结果:
aString:A STRING
string:string
string:String
五、在字符串中搜索子串
1
NSString *string1 = @
"This is a string"
;
2
NSString *string2 = @
"string"
;
3
NSRange range = [string1 rangeOfString:string2];
4
NSUInteger location = range.location;
5
NSUInteger leight = range.length;
6
NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@
"Location:%li,Leight:%li"
,location,leight]];
7
NSLog(@
"astring:%@"
,astring);
8
[astring release];
打印结果:
astring:Location:10,Leight:6