[Objective-c]_[NSString的基本使用]

    NSString是objective-c的字符串,这里总结下NSString的常用方法。

//1. 串初始化
NSString *str1 = [NSString stringWithString:@"test"];
NSLog(@"str1 is %@",str1);

//2.快速创建一个字符串  
NSString *str2 = [[NSString alloc]initWithString:str1];  
NSLog(@"str2 is %@",str2);
NSString *str3 = [NSString stringWithString:str1];
NSLog(@"str3 is %@",str3);  

//3.获取串长度
int l = [str1 length]; 
NSLog([NSString stringWithFormat:@"length = %d", l]); 

//4.创建一个格式化字符串  
NSString *str4 = [[NSString alloc]initWithFormat:@"%d",10];  
NSString *str5 = [NSString stringWithFormat:@"%.2f",10.8099887];  
NSLog(@"str4 = %@",str4);  
NSLog(@"str5 = %@",str5);  
   
//5.比较两个字符串内容是否相等  
if ([str2 isEqualToString:str3]) {  
	 	NSLog(@"str6 is EqualToString str7");  
 	}else{  
 		NSLog(@"str6 is not EqualToString str7");  
 	} 
            
//6.转换为基本数据类型  
NSString *str6 = @"3";  
float f1 = [str8 floatValue];  
NSLog(@"str6 = %.2f",f1); 
           
//7.字符串拆分为数组  
NSString *str7 = @"命 运 就 算 颠 沛 流 离";  
NSArray *array = [str9 componentsSeparatedByString:@" "];  
NSLog(@"array = %@",array);  
NSLog(@"array[0] = %@",array[0]);  

//8.拼接
NSString *str8 = [s stringByAppendingString:@" and test again"];
NSLog(@"string after append is %@",str8);
    
//9.获取子串
NSRange rng = NSMakeRange(5, 4);
NSString *ssub = [str8 substringWithRange:rng];
NSLog(@"sub string is %@", ssub);

//10.从文件中获取字符串
NSString *sFromFile = [[NSString alloc] initWithContentsOfFile:@"Info.plist"];
NSLog(@"file string is %@", sFromFile);
 
//11.从网页上获取字符串
NSURL *url = [[NSURL alloc] initWithString:@"http://www.macfans.com.cn/"];
NSString *sFromUrl = [[NSString alloc] initWithContentsOfURL:url];
NSLog(@"URL string is %@", sFromUrl); 

//12.查询子串
NSString *ssearch = @"girl";
NSString *sfrom = @"find a perfect girl in the world. -- paul liu";
rng = [sfrom rangeOfString:ssearch];
NSLog(@"find a girl in %d,%d", rng.location, rng.length);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值