首页 > 代码库 > OC 基本语法——NSString
OC 基本语法——NSString
NSString 常用方法
// 字符串的初始化
NSString *str = [NSString stringWithFormat:@"^^^^ %@####",dyh ];
// 字符串的拼接
NSString *a1 = [dyh stringByAppendingString:@"22岁"];
NSLog(@"第二个 字符串 = %@",dyh1);
NSString *dyh3 = [dyh stringByAppendingFormat:@" yibin"];
// 计算字符串的长度
NSInteger length = [str3 length];
NSLog(@"length = %ld",length);
NSLog(@"dyh3 is = %@",dyh3);
//截取字符串 从第二个开始截取
NSString *str = [dyh3 substringFromIndex:2];
//截取后的字符串为 : YuHeng Yibin
NSLog(@"str = %@",str);
//截取字符串 :截取位置从0开始截取到索引位置为4的结束
NSString *str1 = [dyh substringToIndex:4];
//截取后的str1 = DuYu
NSLog(@"str1 = %@",str1);
//NSmakeRange (Location:截取位置的地址,length截取的长度)
NSRange range = NSMakeRange(0, 2);
NSString *str2 = [dyh substringWithRange:range];
//截取后的值是 Du
NSLog(@"str2 = %@",str2);
// 判断字符串是否相同
BOOL result = [str3 isEqualToString:@"hello"];
// isEqualToString的返回类型是 bool类型
if (result == YES) {
NSLog(@"相同");
}else {
NSLog(@" 不相同");
}
NSComparisonResult compResult = [str3 compare:@"DuYu "];
switch (compResult) {
case NSOrderedAscending:
NSLog(@" %@ < DuYu ",str3);
break;
case NSOrderedSame:
NSLog(@" = ");
break;
case NSOrderedDescending:
NSLog(@" %@ > DuYu ",str3);
break;
}
// 判断字符串前缀后缀
// 前缀
if([dyh hasPrefix:@"www."]){
NSLog(@"is url");
}else{
NSLog(@"not url");
}
// 后缀
if ([dyh hasSuffix:@".com"]) {
NSLog(@"is url");
}else{
NSLog(@"not url");
}
//分割字符串
NSString * url = @"www.baidu.com";
NSArray *componts = [url componentsSeparatedByString:@"."];
NSLog(@"%@",componts);
//把字符串转换为相印的类型
NSString *str4 = @"123";
int num = [str4 intValue];
NSLog(@"%d",num);
return 0;
OC 基本语法——NSString