关于OC常用字符串函数介绍
1.格式化字符串:stringWithFormat
//1 定义一个字符串
NSString * s = @"My age is";
//2 定义一个整形变量
int myAge = 18;
//3 将字符串s 和 整形变量myAge 组合成一个字符串
NSString * s2 = [NSString stringWithFormat:@"%@%d",s,myAge];
//4 输出打印
NSLog(@"%@",s2);
2.C语言的字符串转化: stringWithUTF8String
//1 定义一个c语言字符串
char *s = "我是c语言字符串";
//2 将其转化为oc的字符串
NSString *str = [NSString stringWithUTF8String:s];
//3 输出打印
NSLog(@"str -- %@",str);
3.将字符串中大写字母变成小写:lowercaseString
//1 定义一个字符串
NSString * s = @"THIS MY STRING";
//2 用lowercaseString转化
NSString * str =[s lowercaseString];
//3 输出打印
NSLog(@"str -- %@",str);
4.将字符串中小写字母变成大写:uppercaseString
//1 定义一个字符串
NSString * s = @"this my string";
//2 用uppercaseString转化
NSString * str =[s uppercaseString];
//3 输出打印
NSLog(@"str -- %@",str);
5.将字符串中单词的首字母大写:capitalizedString
//1 定义一个字符串
NSString * s = @"this my string";
//2 用capitalizedString转化
NSString * str = [s capitalizedString];
//3 输出打印
NSLog(@"str -- %@",str);
6.比较字符串是否相同:有 isEqualToString 和 compare
//1 定义两个字符串
NSString * s1 = @"this my string";
NSString * s2 = @"that my string";
//2 首先用isEqualToString比较
if([s1 isEqualToString:s2]){
NSLog(@"他们是相同的");
}else{
NSLog(@"他们是不同的");
}
//3 用compare比较
int cmp = [s1 compare:s2];
if(cmp==0){
NSLog(@"他们是相同的");
}else if(cmp==1){
NSLog(@"s1是大于s2的");
}else if(cmp==-1){
NSLog(@"s1是小于s2的");
}
7.检查前缀:hasPrefix 和 检查后缀:hasSuffix
//1 定义一个字符串
NSString * s = @"http://my.oschina.net/purpleDog";
//2 用hasPrefix检查前缀是否为http
if([s hasPrefix:@"http"]){
NSLog(@"前缀是http");
}else{
NSLog(@"前缀不是http");
}
//3 用hasSuffix检查后缀是否是purpleDog
if([s hasSuffix:@"purpleDog"]){
NSLog(@"后缀是purpleDog");
}else{
NSLog(@"后缀不是purpleDog");
}
8.字符串截取:substringWithRange
//1 定义一个字符串
NSString * s = @"0123456789";
//2 截取1-3 NSMakeRange(1,3) 1代表从哪个字符开始截取,3代表截取长度;
NSString * str = [s substringWithRange:NSMakeRange(1,3)];
//3 输出打印
NSLog(@"str -- %@",str);
9.获取字符串中的字母:characterAtIndex
//1 定义一个字符串
NSString *s = @"purpleDog";
//2 循环输出字符
for (int i = 0; i < s.length; i++) {
NSLog(@"%c",[s characterAtIndex:i]);
}
10.替换字符串中的一段:stringByReplacingOccurrencesOfString
//1 定义一个字符串
NSString * s = @"purpleDog";
//2 将Dog替换为Cat
NSString * s1 = [s stringByReplacingOccurrencesOfString:@"Dog" withString:@"Cat"];
//3 输出打印
NSLog(@"%@",s1);