NSString *str=[[NSString alloc]initWithFormat:@"123-456-789-000"]; 2 3 //(1)把”-“去掉,并放在数组内 并输出 4 NSArray *arr=[str componentsSeparatedByString:@"-"]; 5 NSLog(@"%@%@%@%@",[arr objectAtIndex:0],[arr objectAtIndex:1],[arr objectAtIndex:2],[arr objectAtIndex:3]); 6 //(2)用空字符代替“-“ 7 NSString *newStr=[str stringByReplacingOccurrencesOfString:@"-" withString:@""]; 8 NSLog(@"%@",newStr);
// // main.m // 作业2 // // Created by syrcfwzx on 16/1/6. // Copyright (c) 2016年 syrcfwzx. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //方法1 NSString* str = @"123-456-789-000"; NSString* newstr =[str stringByReplacingOccurrencesOfString:@"-" withString:@""]; NSLog(@"%@",newstr); //方法2 NSArray* array = [str componentsSeparatedByString:@"-"]; str = [array componentsJoinedByString:@""]; NSLog(@"%@",str); } return 0; }
例子2
// // main.m // 数组 // // Created by syrcfwzx on 16/1/7. // Copyright (c) 2016年 syrcfwzx. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //字符串对象分割 NSString* str = @"how are you"; NSArray* words = [str componentsSeparatedByString:@" "]; NSLog(@"%@",words); //字符串对象的拼接 NSArray* words2 = @[@"one",@"two",@"three"]; NSString* str2 = [words2 componentsJoinedByString:@"-"]; NSLog(@"%@",str2); } return 0; }