字符串修改不起作用?
string modifications are not working?
这是我的代码,在我的 url 字符串中白色 space 没有被代码编码
NSString *str = item.fileArtPath;
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set];
[str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *urlString = [NSURL URLWithString:str];
对于以下字符串:
http://xx.xx.xx.xxx:xx/xx/xx/xx/xxx/Audio Adrenaline.jpg
^^^^^^^^^^^^^^^^^^^^
Audio
后的白色space在我使用字符串替换后没有转换为%20
。在调试中 urlString
是 nil
为什么这样?
来自 NSString Class 参考
Returns a new string made from the receiver by replacing all
characters not in the specified set with percent encoded characters.
这意味着它不会置换调用它的实例。你需要说类似 str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
Same with [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
回想一下 NSString
是 不可变的 。调用方法 stringBy...
returns 修改后的字符串,而不是修改原始字符串。因此你的代码应该重写如下:
str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *search = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
这是我的代码,在我的 url 字符串中白色 space 没有被代码编码
NSString *str = item.fileArtPath;
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
[str stringByAddingPercentEncodingWithAllowedCharacters:set];
[str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *urlString = [NSURL URLWithString:str];
对于以下字符串:
http://xx.xx.xx.xxx:xx/xx/xx/xx/xxx/Audio Adrenaline.jpg
^^^^^^^^^^^^^^^^^^^^
Audio
后的白色space在我使用字符串替换后没有转换为%20
。在调试中 urlString
是 nil
为什么这样?
来自 NSString Class 参考
Returns a new string made from the receiver by replacing all characters not in the specified set with percent encoded characters.
这意味着它不会置换调用它的实例。你需要说类似 str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
Same with [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
回想一下 NSString
是 不可变的 。调用方法 stringBy...
returns 修改后的字符串,而不是修改原始字符串。因此你的代码应该重写如下:
str = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *search = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];