通常情况下,使用for循环可以通过递增,也可以通过递减,使用递减遍历代码如下:
- (void)testFor
{
NSString *string = @"信不信由你";
for (int i = string.length - 1; i >= 0; i--) {
NSLog(@"%c -- %d", [string characterAtIndex:i], i);
}
}
执行正常,但是xcode
会很蛋疼的报出警告因为循环变量类型问题。
这时,可以使用强制类型转换,修改代码如下:
- (void)testFor
{
NSString *string = @"信不信由你";
for (int i = (int)string.length - 1; i >= 0; i--) {
NSLog(@"%c -- %d", [string characterAtIndex:i], i);
}
}
执行正常,不会出现问题,也不再有警告。
当然也可以改变循环变量的类型,改为NSUInteger
,代码如下:
- (void)testFor
{
NSString *string = @"信不信由你";
for (NSUInteger i = string.length - 1; i >= 0; i--) {
NSLog(@"%c -- %d", [string characterAtIndex:i], i);
}
}
现在执行就会出现问题了,因为循环变量是无符号类型,当i为0时,再进行 --
操作会得到正值,而且这个值很大,所以会出现一直循环的情况。这时稍微改下代码就可以解决了:
- (void)testFor
{
NSString *string = @"信不信由你";
for (NSUInteger i = string.length; i > 0; i--) {
NSLog(@"%c -- %d", [string characterAtIndex:i - 1], i - 1);
}
}
这样也可以正常运行了。