简体   繁体   中英

Replace characters in string in swift?

I have a string as "12:66 PM".Now i want to replace string 66 with 60.So i want to check if that after ":" two characters should be replaced with 60 or any value.

please suggest

You can use regexp-search-and-replace:

string.replacingOccurrences(of: "regexp", with: "replacement", options: .regularExpression)

So, in your case:

var time = "12:66 PM"
time.replacingOccurrences(of: ":\\d\\d", with: ":60", options: .regularExpression)
// > "12:60 PM"

Abstracting this into a function is straight-forward:

func replaceMinutes(in time: String, with minutes: String) -> String {
    return time.replacingOccurrences(of: ":\\d\\d", 
                                     with: ":\(minutes)", 
                                     options: .regularExpression)
}

If necessary, you may want to check that the input strings match what you expect:

    nil != time.range(of: "^\\d\\d:\\d\\d [AP]M$", options: .regularExpression)
&&  nil != minutes.range(of: "^\\d\\d$", options: .regularExpression)

If you have trouble understanding how any of this works, I recommend you read up on a) basics of the Swift language and b) regular expressions .

Here Is the Logic how can you do that first of all you have o take last index of your input var

in Java we can do like this

String l_name = input .substring(input .lastIndexOf(":"));

And after That you can replace l_name with your new output with variable i hope it will help..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM