Reputation: 309
I have a string that contains a url. I am trying to check if the url has a space which is invalid.
let url = "http://www.example.com/images/pretty pic.png"
As you can see in this example, there is a space between pretty and pic. Thanks.
Upvotes: 1
Views: 5028
Reputation: 428
For Swift 5
var string = "Hi "
if string.contains(" "){
print("Has space")
}else{
print("Does not have space")
}
Upvotes: 0
Reputation: 12023
extension on String which returns bool would be more elegant solution here
extension String {
public var hasWhiteSpace: Bool {
return self.contains(" ")
}
}
Upvotes: 1
Reputation: 73186
Another alternative: check if the set of characters to the string contain a whitespace
let url = "http://www.example.com/images/pretty pic.png"
url.characters.contains(" ") // true
let url = "http://www.example.com/images/prettypic.png"
url.characters.contains(" ") // false
Upvotes: 5
Reputation: 19524
let url = "http://www.example.com/images/pretty pic.png"
let whiteSpace = " "
if let hasWhiteSpace = url.rangeOfString(whiteSpace) {
print ("has whitespace")
} else {
print("no whitespace")
}
Upvotes: 2
Reputation: 826
Use simple indexOf to find the space.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
Upvotes: 1