Chris
Chris

Reputation: 105

Iterate over a string to remove specific characters swift

I have a string which shows a time in hh:mm:ss:ms and I need to iterate over the string and remove unwanted characters to then display in a label.

So for example if the time string was 00:25:30:00 I'd want the final output to be 25:30 or if the string was 00:25:00:30 it needs to output 25:00:30

I have the below code, which I thought worked until I realised I only want to remove characters when there are two zeros next to each other, so not sure how to achieve this. I'm self teaching myself to code, so apologise if this is a typical noob or stupid question...

    var gTimeString = "00:25:30:00"
    var gTimeStringReduced = ""

//iterate over string and remove zeros
    for char in gTimeString {
        print("character = \(char)")
        if char != "0" {
            gTimeStringReduced.append(char)
            print("reduced: ", gTimeStringReduced)
        }
    }
//remove the colon from the end of the string
    for ch in gTimeStringReduced.dropLast() {
        print(ch)
        // `ch` is a Character. Use `String(ch)` if you need a String.
    }

I've also just realised the above code will always remove the final character whether its a colon or not, which also isn't much use!

All help appreciated!

Upvotes: 1

Views: 282

Answers (1)

Larme
Larme

Reputation: 26086

Since you have always "00:" to remove if it's at the start or ":00" if it's at the end, let's think it that way:

While the string has "00:" at the beginning, we remove it.
While the string has ":00" at the end, we remove it.

In code:

func trimmingZeroTime(str: String) {
    var text = str
    print("Initial: \(text)")
    while text.hasPrefix("00:") {
        text = String(text.dropFirst(3))
    }
    while text.hasSuffix(":00") {
        text = String(text.dropLast(3))
    }
    print("final: \(text)")
}

Sample tests:

trimmingZeroTime(str: "00:25:30:00")
trimmingZeroTime(str: "00:25:00:30:00")
trimmingZeroTime(str: "00:00:25:00:30:00")
trimmingZeroTime(str: "00:00:25:00:00")

Output:

Initial: 00:25:30:00
final: 25:30
Initial: 00:25:00:30:00
final: 25:00:30
Initial: 00:00:25:00:30:00
final: 25:00:30
Initial: 00:00:25:00:00
final: 25

EDIT:

As the author as specified its final use, I recommend to use DateComponentsFormatter instead of a manual parsing.

Upvotes: 1

Related Questions