OC之對不可變字串、可變字串、可變陣列的操作及OC中字串的排序
阿新 • • 發佈:2019-02-07
對不可變字串的操作: NSString*str = [[NSStringalloc]initWithString:@"^封梟^"]; NSLog(@"str = %@",str); NSString*str1 = [NSStringstringWithString:@"-若雪-"]; NSLog(@"str1 = %@",str1); //求字串長度.length NSUIntegerlength = str1.length; NSLog(@"lenth = %lu",length); //字串拼接 NSString*str2 = [str1 stringByAppendingString
字串排序:用compare比較 if([[s1 name]compare: [s2name]] <0) { returnNSOrderedAscending; }elseif([[s1 name]compare: [s2name]] >0){ returnNSOrderedDescending; }else{ returnNSOrderedSame; } 對可變陣列的操作 NSMutableArray*ma = [[NSMutableArrayalloc]initWithObjects:@"她說",@"陰天",@"明天,你好",@"離歌",nil]; [maaddObject:@""]; for(inti = 0; i < array.count; i++) { NSLog(@"%@",array[i]); } //插入 [mainsertObject:@"日不落"atIndex:3]; //刪除 [maremoveObjectAtIndex:3]; for(inti = 0; i < ma.count; i++) { NSLog(@" 3%@",ma[i]); } //替換 [mareplaceObjectAtIndex:4withObject:@"天亮了"]; for(inti = 0; i < ma.count; i++) { NSLog(@" 4%@",ma[i]); } //交換指定位置的元素 [maexchangeObjectAtIndex:2withObjectAtIndex:1]; for(inti = 0; i < ma.count; i++) { NSLog(@" 5%@",ma[i]); } //把int型別轉換為NSNumber物件型別存入陣列 NSNumber*o1 = [NSNumbernumberWithInt:123]; NSNumber*o2 = [NSNumbernumberWithInt:234]; //把float轉換為NSNumber物件存入陣列 NSNumber*o3 = [NSNumbernumberWithFloat:'A']; NSNumber*o4 = [NSNumbernumberWithFloat:'Y']; //把陣列元素取出來,用xxxValue在轉換為原來型別 NSArray*a2 = [NSArrayarrayWithObjects:o1,o2,o3,o4,nil]; intw = [[a2 objectAtIndex:0]intValue]; NSLog(@"a2 = %d",w); floatb = [[a2 objectAtIndex:3]intValue]; NSLog(@"a2 = %.fd",b);