0

Here's a simple code that let us find out if a string contains a dot characters (we don't know how many, we just know that it contains it):

var number: String = "3.14"

if number.contains(".") {
    print("The string contains a dot character")
} else {
    print("There's no dot character")
}

But imagine a situation where user wrongly puts 2 or 3 dots in a line, like this:

var number: String = "3...14"

How to check whether a string contains one dot or several ones?

How to count all the dots in the string?

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • `number.contains(".")` does return true if the string contains one, two or 100 dots. – And what does “several similar characters” mean exactly? – Martin R Jul 14 '19 at 12:59
  • A String is a collection of Characters, therefore the methods from https://stackoverflow.com/questions/31194938/how-to-count-specific-items-in-array-in-swift can be used here as well. – Martin R Jul 14 '19 at 13:12
  • You still did not clarify what “similar characters” are. – Martin R Jul 14 '19 at 13:13
  • Martin, I fixed the heading. – Andy Jazz Jul 14 '19 at 13:18
  • @MartinR, do you know what happened to `count(where:)`? We had it temporarily in Swift 5. – vacawama Jul 14 '19 at 13:25
  • @vacawama: See https://forums.swift.org/t/require-parameter-names-when-referencing-to-functions/27048: "This proposal was ultimately accepted in time for Swift 5, but sadly had to be reverted because it was causing issues with the type checker." – Martin R Jul 21 '19 at 01:47
  • @MartinR, thank you! I really appreciate that you followed up on my question. It's a shame the type inference system got in the way, but that’s some tricky code to get right. It seems to me that they could have renamed it to `countElements(where:)` instead of dropping it entirely. – vacawama Jul 21 '19 at 09:17

1 Answers1

5

You can use filter(_:) on the string and count to get the number of dots:

let str = "3..14"

switch str.filter({ $0 == "." }).count {
case 0:
    print("string has no dots")
case 1:
    print("string has 1 dot")
default:
    print("string has 2 or more dots")
}
vacawama
  • 150,663
  • 30
  • 266
  • 294