NSString

1.初始化

  1. char *str1="C string";//这是C语言创建的字符串

  2. NSString *str2=@"OC string";//ObjC字符串需要加@,并且这种方式创建的对象不需要自己释 放内存

  3. //下面的创建方法都应该释放内存

  4. NSString *str3=[[NSString alloc] init];

  5. str3=@"OC string";

  6.  

  7. NSString *str4=[[NSString alloc] initWithString:@"Objective-C string"];

  8.  

  9. NSString *str5=[[NSString alloc] initWithFormat:@"age is %i,name is%.2f",19,1.72f];

  10.  

  11. NSString *str6=[[NSString alloc] initWithUTF8String:"C string"];//C语言的字符串转换为ObjC字符串

  12.  

  13. //以上方法都有对应静态方法(一般以string开头),不需要管理内存(系统静态方法一般都是自动 释放)

  14. NSString *str7=[NSString stringWithString:@"Objective-C string"];

2.字符串的大小写和比较

  1. NSLog(@""Hello world!" to upper is %@",[@"Hello world!" uppercaseString]); //结果:"Hello world!" to upper is HELLO WORLD!

  2.  

  3. NSLog(@""Hello world!" to lowwer is %@",[@"Hello world!" lowercaseString]); //结果:"Hello world!" to lowwer is hello world!

  4.  

  5. //首字母大写,其他字母小写

  6. NSLog(@""Hello world!" to capitalize is %@",[@"Hello world!" capitalizedString]);

  7. //结果:"Hello world!" to capitalize is Hello World!

  8.  

  9. BOOL result= [@"abc" isEqualToString:@"aBc"];

  10. NSLog(@"%i",result);

  11. //结果:0

  12.  

  13. NSComparisonResult result2= [@"abc" compare:@"aBc"];//如果是[@"abc"caseInsensitiveCompare:@"aBc"]则忽略大小写比较

  14. if(result2==NSOrderedAscending){//-1实际上是枚举值

  15.        NSLog(@"left<right.");

  16. }else if(result2==NSOrderedDescending){//1

  17.        NSLog(@"left>right.");

  18. }else if(result2==NSOrderedSame){//0

  19.        NSLog(@"left=right."); }

  20.        //结果:left>right.

  21. }

3.截取和匹配

NSLog(@"has prefix ab? %i",[@"abcdef" hasPrefix:@"ab"]);
//结果:has prefix ab? 1   YES 头部匹配
       
NSLog(@"has suffix ab? %i",[@"abcdef" hasSuffix:@"ef"]);
//结果:has suffix ab? 1   NO  尾巴匹配
       
NSRange range=[@"abcdefabcdef" rangeOfString:@"cde"];//注意如果遇到cde则不再往后面搜索,如果从后面搜索或其他搜索方式可以设置第二个options参数
if(range.location==NSNotFound){
     NSLog(@"not found.");
}
else{
     NSLog(@"range is %@",NSStringFromRange(range));
}
//结果:range is {2, 3}

4.字符串的分割

NSLog(@"%@",[@"abcdef" substringFromIndex:3]);
//结果:def //从index=3开始直到末尾,包含index=3
       
NSLog(@"%@",[@"abcdef" substringToIndex:3]);
//结果:abc //从index=0开始直到index=3,但是不包含index=3
       
NSLog(@"%@",[@"abcdef" substringWithRange:NSMakeRange(2, 3)]);
//结果:cde
       
NSString *str1=@"12.abcd.3a";
NSArray *array1=[str1 componentsSeparatedByString:@"."];
//字符串分割

NSLog(@"%@",array1);

//

(
   12,
   abcd,
   3a
)

5.其他

NSLog(@"%i",[@"12" intValue]);//类型转换
//结果:12
       
NSLog(@"%zi",[@"hello world,世界你好!" length]);//字符串长度注意不是字节数
//结果:17
       
NSLog(@"%c",[@"abc" characterAtIndex:0]);//取出制定位置的字符
//结果:a
       
const char *s=[@"abc" UTF8String];//转换为C语言字符串
NSLog(@"%s",s);
//结果:abc

 

原文地址:https://www.cnblogs.com/kluan/p/4819441.html