NSString和NSMutableString都是对象类型,是NSObject的子类。NSString是不可变字符串,NSMutableString是可变字符串
一、NSString的创建
1.创建常量字符串:
NSString *str1=@"Hello world! ";
2.先对字符串初始化,然后再赋值:
NSString *str2=[[NSString alloc]init];
str2=@"Hello world!!";
3.带参数创建:
NSString *str3=[[NSString alloc]initWithString:str1];
NSString *str4=[[NSString alloc]initWithFormat:@"%@",str1];
NSString *str5=[[NSString alloc]initWithString:[NSString stringWithFormat:@"%@",str1 ]];
二、字符串的比较
1.isEqualToString方法:用来判断两个字符串是否相等:
if([str1 isEqualToString:str2]){
NSLog(@"YES");
}
else {
NSLog(@"NO");
}
2.compare方法:用来比较两个字符串的大小
int result=[str1 compare:str2];
str1小于str2:result的值为-1;
str1等于str2:result的值为0;
str1大于str2:result的值为1;
三、改写字符串
1.把字符串全部变为大写:
NSString *str6=[str2 uppercaseString];
2.把字符串全部变为小写:
NSString *str7=[str2 lowercaseString];
3.把字符串的首字母换成大写:
NSString *str8=[str2 capitalizedString];
四、NSMutableString的创建
NSMutableString *mutableString=[[NSMutableString alloc]init];
NSString *str9=@"How are you";
NSMutableString *mutableString1=[NSMutableString stringWithFormat:@"%@",str9];
NSMutableString *mutableString2=[NSMutableString stringWithString:@"Hi"];
//拼接
[mutableString appendString:@"Hello world!"];
//拼接
[mutableString appendFormat:@"%@",str9 ];
五、NSMutableString的一些常用方法
1.字符串中删除元素
NSMutableString *mutableString2=[NSMutableString stringWithString:@"This is delegate"];
//删除
[mutableString2 deleteCharactersInRange:[mutableString rangeOfString:@" is" ]];
//从字符串的第四位开始删除3个字节
[mutableString2 deleteCharactersInRange:NSMakeRange(4, 3)];
2.字符串的插入:
NSMutableString *mutableString2=[NSMutableString stringWithString:@"This is delegate"];
[mutableString2 insertString:@" is " atIndex:4];
3.字符串的替换:
NSMutableString *mutableString2=[NSMutableString stringWithString:@"This is delegate"];
[mutableString2 replaceCharactersInRange:NSMakeRange(2, 2) withString:@"at"];