在 iOS 开发中 NSString 字符串对象是使用的最多的,总结一下方法
-(void) testNSString{
int i = 10;
NSString *str = [NSString stringWithFormat:@"%d",i]; //字符串格式化
NSLog(@"%@",str);
str = @"sysprogram 2017";
NSLog(@"%@",str);
NSString *strRet = [str substringToIndex:7];//截取掉下标7之后的字符串
NSLog(@"%@",strRet);
strRet = [str substringFromIndex:2]; //截取掉下标2之前的字符串
NSLog(@"%@",strRet);
strRet = [str substringFromIndex:str.length- 2]; //只获取后面的两位字符串
NSLog(@"%@",strRet);
//设置截取字符串的范围,从第二位到第七位
NSRange rang = NSMakeRange(2, 7);
NSString * strRang = [str substringWithRange:rang];
NSLog(@"rang = %@",strRang);
strRet = [str capitalizedString]; //首字母大写
NSLog(@"首字母大写:%@",strRet);
strRet = [str uppercaseString]; //全部转为大写
NSLog(@"全部大写:%@",strRet);
strRet = [str lowercaseString]; //全部转为小写
NSLog(@"全部小写:%@", strRet);
strRet = [str stringByAppendingString:@"xxx"]; //字符串相加
NSLog(@"%@",strRet);
//查找字符串
rang = [str rangeOfString:@"2017"];
NSLog(@"查找的字符串 index 为 %lu", (unsigned long)rang.location);
//将搜索中的字符串替换成为一个新的字符串
strRet = [str stringByReplacingCharactersInRange:rang withString:@"1999"];
NSLog(@"替换后字符串为%@", strRet);
//将 2017 字符串替换成 1998
strRet = [str stringByReplacingOccurrencesOfString:@"2017" withString:@"1998"];
NSLog(@"替换后字符串为%@", strRet);
//字符串比较区分大小写
if ([str isEqualToString:@"sysprogram 2017"]) {
NSLog(@"字符串完全相等");
}
//字符串开头比较
if([str hasPrefix:@"sys"])
{
NSLog(@"字符串结尾为 sys");
}
//字符串结尾比较
if([str hasSuffix:@"2017"])
{
NSLog(@"字符串结尾为 2017");
}
}
还有更多的方法,待续......