陈斌彬的技术博客

Stay foolish,stay hungry

iOS NSString 截取字符串

1. rangeOfString:截取指定字符串的长度;
2. substringToIndex:7:截取从0 索引到指定索引(7)长度的字符串
3. substringFromIndex:9:截取从指定索引(9)到末尾长度的字符串
4. NSRange range = NSMakeRange(0,7);截取从指定索引(0)到指定(7)长度的字符串
5. substringWithRange:range:截取从指定索引(0)到指定(7)长度的字符串
6. isEqualToString:@"p://www":比较字符串包含关系,区分大小写
7. stringWithFormat:格式化字符串。

void findSubString(){
    NSString *filename = @"config.ini";
    NSString *escapedPath = @"/Users/config.ini";

    //在escapedPath中查找filename
    //NSRange iStart = [escapedPath rangeOfString :filename];
    NSRange iStart = [escapedPath rangeOfString: filename options:NSCaseInsensitiveSearch];
   // NSLog(@"iStart length is %@:",iStart.length);
   // NSLog(@"iStart location is %@:",iStart.location);
    if (iStart.length > 0){
        //获取从escapedPath开始位置到iStart.location-1长度的子字符串
        NSString *subStr = [escapedPath  substringToIndex:iStart.location-1]; 
        NSLog(@"subStr:%@",subStr);

        //获取从escapedPath从iStart.location+1开始到末尾的子字符串
        NSString *extension  = [escapedPath  substringFromIndex:iStart.location]; 
        NSLog(@"extension:%@",extension);    

        NSString *url = @"http://www.sevenuc.com";  
        NSRange range = NSMakeRange(3,7);
        NSString* prefix = [url substringWithRange:range];
        NSLog(@"prefix is:%@",prefix);
        if([prefix isEqualToString:@"p://www"])
        {
            NSLog(@"prefix is equal %@",prefix);
        }
        else {      
            NSLog(@"prefix is not equal %@",prefix);
        }
        //获取url从0开始共7个字符的子字符串 
        if ( [prefix isEqualToString:@"http://"] )
            NSLog(@"http prefix found");
        }
}


void formatString(){
    int documentId=100;
    NSString *documentFileName=@"test.doc";
    NSString *requestSring=[NSString stringWithFormat:@"<files><fileid>%d</fileid><filename>%@</filename></files>",documentId,documentFileName];

    NSLog(@"requestString:%@",requestSring);
}