NSString

NSString对象用于存储文本字符串

·创建NSString对象:
//1.快速创建
NSString *str1 = @"这是 个字符串!";
//2.alloc创建的字符串
NSString *str2 = [[NSString alloc] initWithString:@"通过alloc创建的字符串"];
//3.通过格式化符创建
int a = 100;
NSString *str3 = [[NSString alloc] initWithFormat:@"通过alloc创建,数值是:%d",a];
//4.通过格式化符创建
NSString *str4 = [NSString stringWithFormat:@"通过类方法创建,数值是:%d",a];

比较字符串的大小

NSString *s1 = [NSString stringWithFormat:@"字符串"];
NSString *s2 = [NSString stringWithFormat:@"字符串"];
// 较的是指针地址
if (s1 == s2) {
      NSLog(@"s1 == s2");
}
//比较是字符串里的内容
BOOL isSame = [s1 isEqualToString s2];
if(isSame) {
    NSLog {@"字符串内容一样"};
}

比较字符串

NSString *s1 = [NSString stringWithFormat:@"a"];
NSString *s2 = [NSString stringWithFormat:@"b"];
// 比较大小
NSComparisonResult result = [s1 caseInsensitiveCompare s2];
if (result == NSOrderedAscending) {
      NSLog(@"升序:ab");
}

取得字符串长度

NSString *s = @"abc";
//字符串长度
unsigned int len = [s length];

大小写转换

NSString *hello = @"hello WORLD";
// 全部大写
NSLog(@"%@", [hello uppercaseString]); 
 // 全部小写
NSLog(@"%@", [hello lowercaseString]);
//  首字母大写,其他字母变小写
NSLog(@"%@", [hello capitalizedString]); 

转换为基本数据类型

 NSString *str1 = @"10";
 int a = [str1 intValue];

 NSString *str2 = @"10.25";
 float b = [str2 floatValue];

 NSString *str3 = @"1"; 
BOOL flag = [str3 boolValue];

访问指定位置字符

//结果:b   指定位置是从0开始计算的
 NSString *string = @"abcdef"; 
char s = [string characterAtIndex:1];

字符串的截取

指定位置是从0开始计算的

1.分割字符串

NSString *str = @"aaasdfsdf,bbb,ccc,ddd";
//使用”,”分割 形成不同的字符串在数组中
NSArray *array = [str componentsSeparatedByString:@“,"];

2.截取到指定位置

NSString *string = @"abcdef";
//截取索引为2前面的字符串,   结果为ab,
NSString *subString1 = [string substringToIndex:2];

3.从指定位置截取到末尾

//从索引为1的位置截取到末尾  结果为bcde;
NSString *subString2 = [string substringFromIndex:1];

4.指定范围截取

//NSRange表示范围,(位置, 度)    结果为bc
NSRange range = NSMakeRange(1, 2);
NSString *subString3 = [string substringWithRange:range];

拼接字符串

NSString *str1 = @"ab"; 
//字符串1
NSString *str2 = @"cd"; 
//字符串2
NSString *string1 = [NSString stringWithFormat:@"字符串1:%@, 字符串2:%@",str1,str2];
//结果:字符串1:ab, 字符串2:cd
NSString *string2 = [str1 stringByAppendingString:str2];
//结果:abcd
NSString *string3 = [str1 stringByAppendingFormat:@“追加字符串2:%@",str2];
结果:追加字符串2:cd

查找字符串中的内容

NSString *email = @"[email protected]";
NSString *substring = @"@qq.com";
//在字符串email中查找substring
NSRange range = [email rangeOfString substring];
if (range.location != NSNotFound) {
NSLog(@"%@包含%@",email,substring);
NSLog(@"位置是:%ld, 度是:%ld",range.location,range.length);
} else {
NSLog(@"没找到");
}

替换字符串

//结果:[email protected]
NSString *newEmail = [email stringByReplacingOccurrencesOfString:@"qq.com" withString:@"163.com"];

判断字符串是否有相应的前缀后缀

    NSString *str23 = @"[email protected]";
    BOOL isPrefix = [str23 hasPrefix:@"wxhl"];
    NSLog(@"isPrefix:%d", isPrefix);
    BOOL isSuffix = [str23 hasSuffix:@"co"];
    NSLog(@"isSuffix:%d", isSuffix);

你可能感兴趣的:(NSString)