Reputation: 1071
There are strings starting with empty spaces. How can I find index of any first character except of empty space in such strings?
Upvotes: 1
Views: 2147
Reputation: 539965
You can use indexOf()
with a predicate:
let str = " Hello world"
// Swift 2:
if let index = str.characters.indexOf({ $0 != " "}) {
print(index) // 3
}
// Swift 3:
if let index = str.characters.index(where: { $0 != " "}) {
let pos = str.distance(from: str.startIndex, to: index)
print(pos) // 3
}
Alternatively, use a regular expression search which can be adapted to more general requests, e.g.
// Swift 2:
if let range = str.rangeOfString("\\S", options: .RegularExpressionSearch) {
let index = str.startIndex.distanceTo(range.startIndex)
print(index) // 3
}
// Swift 3:
if let range = str.range(of: "\\S", options: .regularExpression) {
let pos = str.distance(from: str.startIndex, to: range.lowerBound)
print(pos) // 3
}
to find the index of the first non-whitespace character in the string.
Upvotes: 5
Reputation: 5626
You could try an extension like this:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let index = self.characters.indexOf(char) where String(char) != " "{
return self.startIndex.distanceTo(index)
}
return nil
}
}
You could also use an extension to find out if the character is a whitespace. Source here.
extension Character {
func isMemberOfSet(set:NSCharacterSet) -> Bool {
for char in String( self ).utf16 {
if set.characterIsMember( char ) {
return true
}
}
return false
}
}
Call like this:
let isWhiteSpace = char.isMemberOfSet(NSCharacterSet.whitespaceCharacterSet())
Upvotes: 1