NSString作业2:取出字符串“123-456-789-000”中的数字部分,组成一个新的字符串输出

方法1:取出字符串中的数字

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *strOriginal=@"123-456-789-000";
        NSRange rang1={0,3},rang2={4,3},rang3={8,3},rang4={12,3};
        NSString *str1=[strOriginal substringWithRange:rang1];
        NSString *str2=[strOriginal substringWithRange:rang2];
        NSString *str3=[strOriginal substringWithRange:rang3];
        NSString *str4=[strOriginal substringWithRange:rang4];
        NSString *strResult=[[NSString alloc]initWithFormat:@"%@%@%@%@",str1,str2,str3,str4];
        NSLog(@"%@ has been change to %@",strOriginal,strResult);
    }
    return 0;
}

方法2:删除字符串中的“-”

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSMutableString *string=[[NSMutableString alloc]initWithFormat:@"123-456-789-000"];
        NSRange rang=[string rangeOfString:@"-"];
        do{
            [string deleteCharactersInRange:rang];
            rang=[string rangeOfString:@"-"];
        }while(rang.location!=NSNotFound);
        NSLog(@"string after chang:%@",string);
    }
    return 0;
}

 方法3:替换字符串中的“-"为”“(空字符串)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *str=@"123-456-789-000";
        NSString *string=[str stringByReplacingOccurrencesOfString:@"-" withString:@""];
        NSLog(@"string after change:%@",string);
    }
    return 0;
}

 

posted @ 2016-01-07 08:43  零点五  阅读(380)  评论(0编辑  收藏  举报