stringByReplacingOccurrencesOfString无法按预期工作

sud*_*-rf 1 iphone cocoa-touch

有问题.这是我的代码:

Latitude = [TBXML textForElement:lat]; //Latitude & Longitude are both NSStrings
Longitude= [TBXML textForElement:lon];
NSLog(@"LAT:%@ LON:%@",Latitude,Longitude);
NSString *defaultURL = @"http://api.wxbug.net/getLiveWeatherRSS.aspx?ACode=000000000&lat=+&long=-&unittype=1";
newURL = [[defaultURL stringByReplacingOccurrencesOfString:@"+" 
                                                        withString:Latitude]
                                    stringByReplacingOccurrencesOfString:@"-" 
                                                        withString:Longitude];
NSLog(@"%@",newURL);
Run Code Online (Sandbox Code Playgroud)

这是输出:

LAT:-33.92 LON:18.42 
http://api.wxbug.net/getLiveWeatherRSS.aspxACode=000000000&lat=18.4233.92&long=18.42&unittype=1
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,附加代码发生了一些奇怪的事情.我在这里做错了吗?

ken*_*ytm 7

在更换经度之前,字符串是

http://....&lat=-33.92&long=-&...
                ^           ^
Run Code Online (Sandbox Code Playgroud)

系统看到有两个-,因此它们都将被纬度取代.


您应该使用更具描述性的字符串来替换,例如

NSString *defaultURL = @"http://....&lat={latitude}&long={longitude}&unittype=1";
newURL = [defaultURL stringByReplacingOccurrencesOfString:@"{latitude}" 
                                               withString:Latitude];
newURL = [newURL stringByReplacingOccurrencesOfString:@"{longitude}" 
                                           withString:Longitude];
Run Code Online (Sandbox Code Playgroud)

或者只是使用+stringWithFormat:.

NSString* newURL = [NSString stringWithFormat:@"http://....&lat=%@&long=%@&...",
                                              Latitude, Longitude];
Run Code Online (Sandbox Code Playgroud)