2013-02-07 35 views
0

如何僅從此字符串中分隔網址。 「」: 「http://flut.psites.info/api/uploads/13602519341.jpg」} 「字符串中的單獨網址

我做的是這樣的:

arr = [returnString componentsSeparatedByString:@"image"]; 
NSLog(@"********%@",arr); 

self.mImgUrlStr = [arr objectAtIndex:1]; 
NSLog(@"imgUrl: %@",self.mIm gUrlStr); 

這是原始的字符串 {」消息「:」true「,」image「:」http://flut.psites.info/api/uploads/13602544571.jpg「}」

從這個唯一的url需要。

+0

請張貼一些代碼.. –

+2

是,爲了呼應@Aman ...發佈更多的你試圖分開什麼(例如更多「'returnString'」)。它看起來/聞起來像JSON。 –

+0

嘗試使用NSScanner。示例在這裏 - > http://stackoverflow.com/questions/594797/how-to-use-nsscanner。你可以掃描到http並從那裏繼續。或者,你可以嘗試一個JSON解析器,儘管這可能是矯枉過正的。 – esh

回答

2

這裏有一個更好的方式來解析你的JSON輸出:

// take string and put it into an NSData object (which NSJSONSerialization can work with) 
NSData * dataFromString = [returnString dataUsingEncoding: NSUTF8StringEncoding]; 
if(dataFromString) 
{ 
    NSError * error = NULL; 
    NSDictionary * resultDictFromJSON = [NSJSONSerialization JSONObjectWithData: dataFromString options: 0 error: &error]; 
    if(resultDictFromJSON == NULL) 
    { 
     NSLog(@"error from JSON parsing is %@", [error localizedDescription]); 
    } else { 
     NSString * imageURLString = [resultDictFromJSON objectForKey: @"image"]; 
     if(imageURLString) 
     { 
      NSLog(@"here's your image URL --> %@", imageURLString); 
     } else { 
      NSLog(@"hmmm, I couldn't find an \"image\" in this dictionary"); 
     } 
    } 
} 
1

猜你可以用一些基本的字符串組合來解決這個問題。嘗試這個;

NSString *firstString = @"http://flutterr.pnf-sites.info/api/uploads/13602519341.jpg"; 
NSArray *strComponents = [firstString componentsSeparatedByString:@"/"]; 

NSString *finalString = [NSString stringWithFormat:@"%@//%@", [strComponents objectAtIndex:0], [strComponents objectAtIndex:2]]; 
NSLog(finalString); 

此打印出:

2013-02-07 11:19:39.167 TestProject[91226:c07] http://flutterr.pnf-sites.info 

希望這有助於!

+0

不,不是。 firstString是我所需要的。 –

+0

啊,我明白了。你可以在你發佈的代碼之前做一個'returnString'的NSLog,讓我知道打印出來的是什麼? – Madhu

+0

以上是URL,「:」這是多餘的不是必需的,並且}括號在結尾不是必需的。 –