5

In a program I'm writing, I need to check to see if a character is a space (" "). Currently have this as the conditional but it's not working. Any ideas? Thanks in advance.

for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){

    let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];

//operations

    if(String(charBeingExamined) == " "){

    //more operations

    }
}
TomLisankie
  • 3,785
  • 7
  • 28
  • 32

5 Answers5

4

The code below is how I solved this problem with a functional approach in Swift. I made an extension (two, actually), but you could easily take the guts of the function and use it elsewhere.

extension String {
    
    var isWhitespace: Bool {
        guard !isEmpty else { return true }
        
        let whitespaceChars = NSCharacterSet.whitespacesAndNewlines
        
        return self.unicodeScalars
            .filter { !whitespaceChars.contains($0) }
            .count == 0
    }
    
}

extension Optional where Wrapped == String {
    
    var isNullOrWhitespace: Bool {
        return self?.isWhitespace ?? true
    }
    
}
Dov
  • 15,530
  • 13
  • 76
  • 177
3

The following code works for me. Note that it's easier to just iterate over the characters in a string using 'for' (second example below):

var s = "X yz"
for var i = 0; i < s.characters.count; i++ {
    let x = s[s.startIndex.advancedBy(i)]
    print(x)
    print(String(x) == " ")
}

for c in s.characters {
    print(c)
    print(String(c) == " ")
}
Michael
  • 8,891
  • 3
  • 29
  • 42
1

String:

let origin = "Some string with\u{00a0}whitespaces" // \u{00a0} is a no-break space

Oneliner:

let result = origin.characters.contains { " \u{00a0}".characters.contains($0) }

Another approach:

let spaces = NSCharacterSet.whitespaceCharacterSet()
let result = origin.utf16.contains { spaces.characterIsMember($0) }

Output:

print(result) // true

Not sure what you want to do with the spaces, because then it could be a bit simpler.

Eendje
  • 8,815
  • 1
  • 29
  • 31
0

just in your code change " " -> "\u{00A0}"

for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){
    let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];
    if(String(charBeingExamined) == "\u{00A0}"){
        //more operations
    }
}
Daniel Bastidas
  • 1,795
  • 1
  • 9
  • 15
0

To test just for whitespace:

func hasWhitespace(_ input: String) -> Bool {
    let inputCharacterSet = CharacterSet(charactersIn: input)
    
    return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty
}

To test for both whitespace and an empty string:

func hasWhitespace(_ input: String) -> Bool {
    let inputCharacterSet = CharacterSet(charactersIn: input)
    
    return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty || inputCharacterSet.isEmpty
}
Evan R
  • 875
  • 13
  • 27