美文网首页
iOS NSString去除空格换行符,解决NSUrl为nil问

iOS NSString去除空格换行符,解决NSUrl为nil问

作者: 你的小福蝶 | 来源:发表于2019-02-19 16:21 被阅读2次

有时需求会是从后端获取url然后拼接字符再请求,这里会需要对未知NSString进行去除空格换行等操作,否则NSUrl会是nil!

NSString *url = @"www.baidu.co m";//后端获取得到(里面带有空格换行等)
NSString *name = @"小明";
//中文转编码
NSString *nameCode = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//拼接
NSString *urlStr = [NSString stringWithFormat:@"%@&name=%@",url,nameCode];

//去除空格和换行
urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
urlStr = [urlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
urlStr = [urlStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
urlStr = [urlStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSURL *urlU = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:urlU];
[self.currentWebView loadRequest:request];

相关文章

网友评论

      本文标题:iOS NSString去除空格换行符,解决NSUrl为nil问

      本文链接:https://www.haomeiwen.com/subject/nwdfyqtx.html