一些方法需要指定一个范围确定字符串,包括开始索引数和字符数,索引数以0开始。在Foundation的框架中的一些方法,使用了特殊的数据类型NSRange创建范围对象。实际上,它是结构typedef定义,包含location和length两个成员。
现在有如下代码:
#import <Foundation/Foundation.h>
int main ()
{
@autoreleasepool {
NSString *str1 =@"this is string A";
NSString *res;
NSRange subRange; //这里没有星号不是引用
//从字符串中提取前3个字符
res = [str1 substringToIndex: 3];
NSLog(@"First 3 chars of str1:%@",res);
//提取从索引5开始直到结尾的子字符串
res = [str1 substringFromIndex: 5];
NSLog(@"Chars from index 8 through 13:%@",res);
//提取从索引8开始到索引13的子字符串(6个字符)
res = [[str1 substringFromIndex:8]substringToIndex:6];
NSLog(@"Chars from index 8 through 13:%@",res);
//更简单的方法
res = [str1 substringWithRange:NSMakeRange(8,6)];
NSLog(@"Chars from index 8 through 13:%@",res);
//从另一个字符串中查找一个字符串
subRange = [str1 rangeOfString: @"string A"];
NSLog(@"String is at index %lu,length is %lu",subRange.location,subRange.length);
subRange = [str1 rangeOfString: @"string B"];
if (subRange.location ==NSNotFound) {
NSLog(@"String not found");
}
else
NSLog(@"String is at index %lu,length is %lu",subRange.location,subRange.length);
}
return 0;
}
运行结果:2014-08-24 10:40:15.737 testOC[622:303] First 3 chars of str1:thi
2014-08-24 10:40:15.739 testOC[622:303] Chars from index 8 through 13:is string A
2014-08-24 10:40:15.739 testOC[622:303] Chars from index 8 through 13:string
2014-08-24 10:40:15.740 testOC[622:303] Chars from index 8 through 13:string
2014-08-24 10:40:15.740 testOC[622:303] String is at index 8,length is 8
2014-08-24 10:40:15.741 testOC[622:303] String not found
Program ended with exit code: 0
substringToIndex:方法创建了一个子字符串,包含首字符到指定的索引数,但不包括该索引值对应的字符。对于所有采用索引数作为参数的字符串方法,如果提供的索引数对改字符无效,就会获得Range or index out of bounds的出错消息。substringFromIndex: 方法返回了一个子字符串,它从接受者指定的索引字符开始,直到字符串的结尾。
使用substringWithRange:方法能够一步完成我们刚刚用substringToIndex:和substringFromIndex: 两步所做的工作,接受一个范围。返回指定范围的字符。特殊函数
NSMakeRange (8,6)
根据参数创建一个范围,并返回结果。这个结果可以作为substringWithRange:方法的参数。
要在另一个字符串中查找一个字符串,可以使用rangeOfString:方法。如果在接收者中找到指定的字符串,则返回的范围是找到的精确的位置。然而,如果没有找到字符串,则返回的location成员被设置为NSNotFound。例如:
subRange = [str1 rangeOfString: @"string A"];
把方法返回的NSRange结构赋值给NSRange变量subRange。一定要要注意。subRange不是对象变量,而是一个结构变量(并且程序中的subRange声明不包括星号,这通常意味着不是在处理一个对象,不过id类型是个例外)。
本文介绍Objective-C中如何使用不同方法来操作字符串,包括提取子字符串、查找子串位置等常见任务。通过具体示例展示了substringToIndex、substringFromIndex及substringWithRange等方法的使用技巧。

被折叠的 条评论
为什么被折叠?



