1

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

3
  • Are you just replacing characters after :, or are you trying to change a date / time value? If it's the latter, there are better ways to handle this Commented Jan 11, 2017 at 12:31
  • This is a basic string processing question. SO is not a place to get others to write your code for you. Make an attempt at your own solution to the problem and we'll help you get it working. Commented Jan 11, 2017 at 14:12
  • Or, as Ashley rightly points out, it might be a date and time processing problem. You should probably step back and describe what you're trying to do in more general terms, and your current approach. If you're trying to manipulate dates and times there are indeed better ways to do it. Commented Jan 11, 2017 at 14:14

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

-5

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.