OC中提供了NSString类,用于处理字符串对象,OC对象的字符串必须以@开头,引号当中是字符串的内容,例如@"abc"。OC中有两个字符串类:NSString(不可变字符串)和NSMutableString(可变字符串)
1、NSString(不可变字符串)
(1)创建
NSString *str = @"我是一个字符串";
int a = 1;
NSString *str = [NSString stringWithFormat:@"%i",a];//创建一个格式化字符串
//用其他字符串创建
NSString *str1 = [NSString stringWithString:str];
//用C语言创建
char *c = "Objective-C";
NSString *str = [NSString stringWithUTF8String:c];
(2)将一个.txt文件转化为NSString字符串
NSString *contentStr = [NSString stringWithContentOfFile:[[NSBundle mainBundle] pathForResource:@"小说" ofType:@"txt"]];
(3)常用方法
//大小写转化
[str uppercaseString];//将字符串str转化成大写
[str lowercaseString];//将字符串str转化成小写
[str capitalizedString];/将字符串str首字母转化成大写
//截取字符串
NSString *str1 = [str substringToIndex:5];//从0到指定位置[0,5)
NSString *s1=[str substringFromIndex:2];//从指定位置到末尾[index,length-1]
NSRange rang=NSMakeRange(3, 5);
NSString *s2=[str substringWithRange:rang];//截取一个区间
NSRange range=[str rangeOfString:@"llo"];
//获取子串在字符串中的位置
NSLog(@"location=%lu,length=%lu",range.location,range.length);
//遍历字符串
for (int index=0; index<=[str length]-1; index++) {
char c=[str characterAtIndex:index];
NSLog(@"%c",c);
}
//追加字符串
NSString *str5=@"Hello";
NSString *strNew=[str5 stringByAppendingString:@" World"];
NSLog(@"%@",strNew);
//格式化追加
NSString *strNe=[str5 stringByAppendingFormat:@"%f,%i",3.14,2];
NSLog(@"%@",strNe);
//将字符串分割成字符数组
NSString *uri=@"userid=1&type=2&flag=edit";
NSArray *array=[uri componentsSeparatedByString:@"&"];
NSLog(@"%@",array);
//判断邮箱是否是163邮箱/hasSuffix/hasPrefix
NSString *ema=@"xxxx@163.com";
if ([ema hasSuffix:@"163.com"]) {
NSLog(@"%@是163邮箱",ema);
}
else
NSLog(@"%@不是163邮箱",ema);
//转换为C语言字符串
const char *cemail=[ema UTF8String];
NSLog(@"%s",cemail);
//字符串比较compare返回一个枚举类型
//NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending
NSString *str1=@"abc";
NSString *str2=@"abd";
if ([str1 compare:str2]==NSOrderedDescending) {
NSLog(@"str1>str2");
}
else
NSLog(@"str1<=str2");
//字符串转换为数字
NSString *str3=@"123";
int m=[str3 intValue];//floatValue,doubleValue
2、 NSMutableString(可变字符串)NSMutableString是NSString 的子类,NSString 包含的方法可用于NSMutableString
//创建一空的字符串
NSMutableString *str=[NSMutableString string];
//创建一个指定大小的字符串
NSMutableString *str1=[NSMutableString stringWithCapacity:18];
NSMutableString *str2=[NSMutableString stringWithString:@"hello"];
//赋值,把原来的字符串替换掉
[str2 setString:@"world"];
//拼接字符串appendString/appendFormat
[str2 appendString:@" oc"];
NSLog(@"%@",str2);
[str2 appendFormat:@",%@,%.2f",@"xxx",59.8];
NSLog(@"%@",str2);
//插入字符串
[str2 insertString:@" of" atIndex:5];
//删除指定范围的字符串
NSMutableString *str3=[NSMutableString stringWithString:@"hello world"];
NSRange range=NSMakeRange(6, 5);
[str3 deleteCharactersInRange:range];
//替换操作
NSRange rang163=[em3 rangeOfString:@"163"];
[em3 replaceCharactersInRange:rang163 withString:@"126"];