john tully
john tully

Reputation: 309

Check if string has a space

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

Answers (5)

Muhammad Ariful Islam
Muhammad Ariful Islam

Reputation: 428

For Swift 5

 var string = "Hi "
    if string.contains(" "){
        print("Has space")
    }else{
        print("Does not have space")
    }

Upvotes: 0

Suhit Patil
Suhit Patil

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

dfrib
dfrib

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

Steve Rosenberg
Steve Rosenberg

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

rahil sharma
rahil sharma

Reputation: 826

Use simple indexOf to find the space.

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

Upvotes: 1

Related Questions