替换 URL 中出现的空格
我在 iPhone 应用程序中有一个可以使用的 URL。但问题是它的 URL 中有一些空格。我想用“%20”替换空格。我知道有 stringByReplacingOccurencesOfString 和 stringByAddingPercentEscapesUsingEncoding 方法。我也用过它们。但他们不为我工作。空格被一些不寻常的值替换。
我将这些方法应用于 NSString
的实例。
I have a URL in an iPhone application to work with. But the problem is that it has some spaces in the URL. I want to replace the spaces with '%20'. I know that there are the stringByReplacingOccurencesOfString
and stringByAddingPercentEscapesUsingEncoding
methods. I also have used them. But they are not working for me. The spaces are replaced by some unusual values.
I'm applying those methods on an instance of NSString
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
替换 url 中的空格的正确格式是:
Swift 4.2 、 Swift 5
Swift 4
Objective C
或
iOS 9 及更高版本
The correct format for replacing space from url is :
Swift 4.2 , Swift 5
Swift 4
Objective C
or
iOS 9 and later
Swift 2.0
输出:
Swift 2.0
Output:
要替换 SWIFT 3 中的出现:
To replace occurence in SWIFT 3 :
Swift 4
使用 replacementOccurrences 方法替换空白的另一种方法:
这会将空白 (" ") 替换为 '%20'
Swift 4
Another way to replace an empty space with replacingOccurrences method:
That will replace the empty space (" ") with '%20'
雨燕5
Swift 5
最快的解决方案:只需使用 stringy 方法...
.replacingOccurrences(of: " ", with: "%20")
...在字符串末尾,它就会按照它说的那样进行。
Apple 应该感到尴尬的是,他们的 URL(string: ) 方法不会自动执行此操作(以及更多操作)。现在是 2023 年,我浪费了 3 个小时来找到这个半途而废的解决方案。
我的具体示例是在 cellForItemAt 内部并且与选项有关。
你可以长时间摆弄 .addingPercentEncoding,尝试 NSURL 废话,使用显而易见的东西你会更快。苹果很糟糕,而且应该让这个问题变得非常容易,因为这是一个如此普遍的问题。再说一遍,他们在开车时睡着了,而且他们的文档也很糟糕。
The quickest solution: just use the stringy method...
.replacingOccurrences(of: " ", with: "%20")
...at the end of your string, and it will do as it says.
Apple should be EMBARRASSED that their URL(string: ) method doesn't automatically do this (and more). It's 2023 and I wasted 3 hours finding this half-assed solution.
My specific example was inside cellForItemAt and having to do with optionals.
You can fuddle with .addingPercentEncoding for a long time, try NSURL nonsense, and you'll just be faster with using the obvious. Apple sucks, and should've made this painfully easy since it's such a common problem. Again, they are asleep at the wheel, and their documentation is AWFUL too.
希望这会起作用
它会从网址中删除所有类型的空格。
Hope this will work
It will remove all kind of spaces from the url.
Swift 5.3,清除字符串空间,
Swift 5.3, clear space your string,
SWIFT 3.1
使用replaceOccurrences 替换空白的简单方法:
SWIFT 3.1
Simple way to replace an empty space with replacingOccurrences:
斯威夫特 4、iOS-9
Swift 4, iOS-9
Swift 4 解决方案。您只需传递一个字符串,它就会用 %20 填充空格,并将“http://”添加到字符串的开头。相当甜蜜!
A Swift 4 solution. You simply pass through a string and it fills spaces with %20 and adds "http://" to the beginning to the string. Pretty sweet!