1.定义一个字符串a, 截取a 的某一个部分,复制给b, b必须是int型
- <p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "> <span style="color: rgb(114, 52, 169); line-height: 16px; ">NSString</span> *a = <span style="color: rgb(202, 44, 37); line-height: 16px; ">@"1.2.30"</span>;</p><p style="font-family: Menlo; font-size: 11px; color: rgb(65, 16, 129); "> <span style="color: rgb(182, 28, 163); line-height: 16px; ">int</span><span style="color: rgb(0, 0, 0); line-height: 16px; "> b= [[a</span> substringWithRange<span style="color: rgb(0, 0, 0); line-height: 16px; ">:</span>NSMakeRange<span style="color: rgb(0, 0, 0); line-height: 16px; ">(</span><span style="line-height: 16px; ">4</span><span style="color: rgb(0, 0, 0); line-height: 16px; ">,</span><span style="line-height: 16px; ">2</span><span style="color: rgb(0, 0, 0); line-height: 16px; ">)]</span> intValue<span style="color: rgb(0, 0, 0); line-height: 16px; ">]; </span></p><p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "> <span style="color: rgb(65, 16, 129); line-height: 16px; ">NSLog</span>(<span style="color: rgb(202, 44, 37); line-height: 16px; ">@"a:%@ \n"</span>,a );</p><p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "><span style="color: rgb(65, 16, 129); line-height: 16px; "> NSLog</span>(<span style="color: rgb(202, 44, 37); line-height: 16px; ">@"b:%d"</span>,b );</p><p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "> </p><p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "><strong>Output : 2011-07-05 11:49:08.170 Q[4005:207] a:1.2.30 </strong></p><p style="color: rgb(51, 51, 51); font-family: Menlo; font-size: 11px; "><strong>2011-07-05 11:49:08.172 Q[4005:207] b:30</strong></p>
复制代码
解析如下:substringWithRange: 专门截取字符串的一块肉 NSMakeRange(4,2) 从第4个字符开始截取,长度为2个字符,(字符串都是从第0个字符开始数的哦~!) b = [a intValue]; 将 a 转换为 整数型 b = [a floatValue]; 将 a 转换为 小数型 b = [a boolValue]; 将 a 转换为 布尔型(true / false) b = [a integerValue]; 将 a 转换为 整数型 b = [a longLongValue]; 将 a 转换为 长整型
2。 字符串截取到第n位 (substringToIndex: n)(第n 位不算再内)
- (void)viewDidLoad { NSString *a = @"i like long dress"; NSString *b = [a substringToIndex:4]; NSLog(@"\n b: %@",b); } b: i li
3。字符串从第n 位开始截取,直到最后 (substringFromIndex:n)(包括第 n 位)
- (void)viewDidLoad { NSString *a = @"i like long dress"; NSString *b = [a substringFromIndex:4]; NSLog(@"\n b: %@",b); }
b: ke long dress 。NSMutableString 为可变的字符串 NSString 为不可变的字符串
-(void)viewDidLoad { NSMutableString *a = [[NSMutableString alloc]initWithString:@"123456798"]; NSLog(@" \n a: %@\n",a); [a deleteCharactersInRange:NSMakeRange(1,2)]; NSLog(@" \n a: %@\n",a); [a release]; }
2011-07-05 20:59:34.169 Q[9069:207] a: 123456798 2011-07-05 20:59:34.171 Q[9069:207] a: 1456798
|