首页 > 代码库 > 字符串截取

字符串截取

1.字符串的截取

  • - (NSString *)substringFromIndex:(NSUInteger)from;
    • 从指定位置from开始(包括指定位置的字符)到尾部
    NSString *str = @"<head>小码哥</head>";    str = [str substringFromIndex:7];    NSLog(@"str = %@", str);输出结果: 小码哥</head>
  • - (NSString *)substringToIndex:(NSUInteger)to;

  从字符串的开头一直截取到指定的位置to,但不包括该位置的字符

    NSString *str = @"<head>小码哥</head>";    str = [str substringToIndex:10];    NSLog(@"str = %@", str);输出结果: <head>小码哥
  • - (NSString *)substringWithRange:(NSRange)range;

  按照所给出的NSRange从字符串中截取子串

    NSString *str = @"<head>小码哥</head>";    NSRange range;    /*    range.location = 6;    range.length = 3;    */    range.location = [str rangeOfString:@">"].location + 1;    range.length = [str rangeOfString:@"</"].location - range.location;    NSString *res = [str substringWithRange:range];    NSLog(@"res = %@", res);输出结果: 小码哥

 

字符串截取