如何用objective-c中的破折号替换空格?

时间:2016-11-04 07:21:53

标签: ios objective-c iphone xcode

嘿民谣我正在使用api来搜索电影现在问题是当我在UISearchBar中键入单个单词时它可以正常工作但是当我为另一个单词输入空格时它会起作用。接近查询= %@当我输入单个单词时它可以工作但是当我用空格键入另一个单词时它不会

NSString *movieName=searchBar.text;
NSString *movieString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/search/movie?query=%@&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

5 个答案:

答案 0 :(得分:2)

您不需要使用Dash替换Space,这是您对URL编码字符串

的新功能

以下是将字符串编码为URL Encode

的示例
NSString *movieName=searchBar.text;
movieName = [movieName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];
NSString *movieString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/search/movie?query=%@&api_key=c4bd81709e87b1209433c49",movieName];
NSURL *url=[NSURL URLWithString:movieString];

答案 1 :(得分:0)

使用

formattedString = [originalString stringByReplacingOccurrencesOfString:@" " withString:@"-"];

答案 2 :(得分:0)

请参阅此代码。

NSString *movieName=searchBar.text;
NSString* replacedMovieName = [movieName stringByReplacingOccurrencesOfString:@" " withString:@"_"];

希望这有帮助。

答案 3 :(得分:0)

无需用短划线替换空格,需要在创建NSURL之前在字符串中添加百分比退出

使用NSString类方法:

-(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

像,

NSString *movieName=searchBar.text;

//This is what you need
movieName=[movieName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString *movieString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/search/movie?query=%@&api_key=c4bd81709e87b1209433c49",movieName];

NSURL *url=[NSURL URLWithString:movieString];

<强> OR

或者您可以执行以下操作(非最佳方法):

NSString *movieName=searchBar.text;

//This is what you need
movieName = [movieName stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString *movieString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/search/movie?query=%@&api_key=c4bd81709e87b1209433c49",movieName];

NSURL *url=[NSURL URLWithString:movieString];

答案 4 :(得分:0)

control.disable();