Objective-C 字符串

2017-07-29  本文已影响0人  ysweiwei

字符串的大小比较

 NSString *string1 = @"abc";
 NSString *string2 = @"bcd"
 NSComparisonResult compareResult = [string1 compare:string2];
 if (compareResult<0) {
        NSLog(@" %@<%@",string1,string2);

    }else if(compareResult>0){
          NSLog(@" %@>%@",string1,string2);
    }else{
         NSLog(@" %@=%@",string1,string2);
    }

重索引值为1的位置开始截取子串(包含1的位置),一直截到最后

NSString *substring  =[@"abcdefg" substringFromIndex:1];
 NSLog(@"%@",substring);

字符串拼接

//在原有的字符串后面追加一个字符串
    NSString *appendString = [@"abc"stringByAppendingString:@"def"];
    NSLog(@"%@",appendString);
//在原有的字符串后面追加一个格式化字符串
    NSString *appendString1 = [@"abc"stringByAppendingFormat:@"%d",123];
    NSLog(@"%@",appendString1);

字符串替换

    NSString *contentString = @"hi,dsb";
    NSString *replaceString = [contentString stringByReplacingOccurrencesOfString:@"sb" withString:@"*****"];
    NSLog(@"%@",replaceString);

判断一个字符串是否以http开头,以png结尾,如果是,输出是一个有效链接,如果不是,输出链接错误。

 NSString *picURLString = @"http://www.lanou3g.com/icon.png";
    if ([picURLString hasPrefix:@"http" ] && [picURLString hasSuffix:@"png" ]) {

        NSLog(@"有效链接picURLString:%@",picURLString);
    }else{
        NSLog(@"链接错误");
    }

判断一个字符串是否是手机号(特点:11位数字,以13或14或15或17或18开头)

NSString *s = @"182123423454";
    if ( (s.length ==11) &&([s hasPrefix:@"13"] ||[s hasPrefix:@"14"]||[s hasPrefix:@"15"]||[s hasPrefix:@"17"]||[s hasPrefix:@"18"])) {
        NSLog(@"%@这个字符串是手机号",s);
        
    }else{
         NSLog(@"%@这个字符串不是手机号",s);
    }

NSString *htmlString = @“<html><head><title>震惊,深夜温强竟然做出这种事</title></head><body><p>从前有座山,山里有座庙,庙里有个老温强和一个小温强,老温强对小温强说:\”嘿嘿嘿"</p></body></html>";
要求:1.将上面这个字符串中的<title></title>中间的内容作为一个新的字符串提取出来
2.将上面这个字符串中的<p></p>中间的内容作为一个新的字符串提取出来
注意:<title></title>和<p></p>假设位置不固定,不要人为的查位置截取

 NSString *htmlString = @"<html><head><title>震惊,深夜温强竟然做出这种事</title></head><body><p>从前有座山,山里有座庙,庙里有个老温强和一个小温强,老温强对小温强说:\"嘿嘿嘿\"</p></body></html>";
     NSRange range1 =[htmlString rangeOfString:@"<title>"];
     NSRange range2 =[htmlString rangeOfString:@"</title>"];
     NSString * ss= [htmlString substringWithRange:NSMakeRange(range1.location+7, range2.location-range1.location-7)];
      NSLog(@"%@\n",ss);
    
    NSRange range3 =[htmlString rangeOfString:@"<p>"];
    NSRange range4 =[htmlString rangeOfString:@"</p>"];
    NSString * ss1= [htmlString substringWithRange:NSMakeRange(range3.location+3, range4.location-range3.location-3)];
    NSLog(@"%@\n",ss1);

上一篇 下一篇

猜你喜欢

热点阅读