NSString类用于处理字符串对象,以@开头,引号当中则是字符串的内容,一旦创建就不可以修改。
1.字符串的创建
NSString *string = @"创建一个字符串常量";//创建一个字符串常量
NSString *string = [[NSString alloc] init];//创建一个空的字符串
NSString *string = [[NSString string];//创建一个空的字符串,类方法
NSString *string = [[NSString alloc] initWithString:@"快速创建一个字符串"];//快速创建字符串;
NSString *string = [[NSString stringWithString:@"快速创建一个字符串"];//创建一个字符串常量
2.快速创建一个格式化字符串
NSString *string = [[NSString alloc] initWithFormat:@"%d",number];
NSString *string = [NSString stringWithFormat:@"浮点数%f",number];
3.比较字符串
NSString *string1 = [[NSString alloc] initWithFormat:@"test"];
NSString *string2 = [[NSString alloc] initWithFormat:@"test"];
if ([string1 isEqualToString:string2]) {
NSLog(@"测试两个字符串是否相等");
}
4.比较字符串时候为同一个对象(内存地址是否相同)
if ( string1 == string2) {
NSLog(@"string1的地址:%p,string2的地址:%p",string1,string2);
NSLog(@"比较两个对象是否为同一对象,也就是比较地址");
}
5.比较字符串的先后顺序
NSString *string1 = [[NSString alloc] initWithFormat:@"a"];
NSString *string2 = [[NSString alloc] initWithFormat:@"b"];
NSLog(@"[string1 caseInsensitiveCompare:string2]:%ld",[string1 caseInsensitiveCompare:string2]);
6.求字符串的长度
NSString *stirng = [[NSString alloc] initWithFormat:@"sting length"];
NSUInteger *length = [string length];//求字符串的长度
7.改变字符串的大小写
NSString *string = @"hello WORLD";
NSLog(@"%@",[string uppercaseString]);//全部大写
NSLog(@"%@",[string lowercaseString]);//全部小写
NSLog(@"%@",[string capitalizedString]);//首字母大写,其他字母小写
8.将字符串转换成基本数据类型
NSString *string = @"3.14135";
NSLog(@"%d",[string boolValue]);//转换成BOOL类型
NSLog(@"%f",[string floatValue]);//转换成浮点类型
NSLog(@"%f",[string doubleValue]);//转换成双精度类型
NSLog(@"%d",[string intValue]);//转换成整形
9.将字符串转换成数组
NSString *string = @"Hello World My Friend";
NSArray *array = [string compinentsSeparatedByString:@" "];
10.字符串的截取与拼接
NSString *string = [[NSString alloc] initWithFormat:@"abcdef"];
NSString *string1 = [string substringToIndex:2];//截取从字符串的开头到制定个位置,不包过该位置的字符串
NSString *string2 = [string substringFromIndex:2];//截取从指定位置开始(包过指定位置的字符)之后的全部字符串
11.根据提供好的范围截取字符串
NSRange rang;
rang.location = 2;
rang.length = 2;
NSString *string = [string substringWithRange:rang];//从第二个位置开始截取长度为2的字符串
12.拼接字符串
NSString *string1 = @"Hello" ;
NSString *string2 = @"World";
NSString *string = [[NSString alloc] initWithFormat:@"这是拼接的字符串:%@ and %@",str1,str2];
NSString *string = [string1 stringByAppendingFormat:@"%@",string2];
NSString *string = [string stringByAppendingString:str2];
13.查询字符串
NSString *string = @"adaadslwsdsfncxdssd";
NSRage rang = [string rangOfString:@"sfnc";
if(range.location != NSNotFound)
{
NSLog(@"找到了该字符串");
}
14.比较字符串
NSString *string = @"Hello World";
NSComparisonResult result1 = [string compare:@"hello World"];
NSComparisonResult result2 = [sting compare:@"hello World" option:NSLiteralSearch];//比较字符串,区分大小写
NSComparisonResult result3 = [string compare:@"hello World" option:NSCaseInsesitiveSearch range:NSMakeRange(0,5)];//比较字符串,不区分大小写