xcode 快速替换字符串中的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41590887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:43:24  来源:igfitidea点击:

Replace characters in string in swift?

iosswiftxcodestring

提问by iOSGuy

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.

我有一个字符串为“12:66 PM”。现在我想用 60 替换字符串 66。所以我想检查“:”之后的两个字符是否应该替换为 60 或任何值。

please suggest

请建议

回答by Raphael

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 languageand b) regular expressions.

如果您无法理解其中任何一个是如何工作的,我建议您阅读 a) Swift 语言的基础知识和 b)正则表达式

回答by Nitin Thakor

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

这是逻辑,你怎么能首先做到这一点,你有 o 取输入变量的最后一个索引

in Java we can do like this

在 Java 中我们可以这样做

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

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

在那之后,您可以用带有变量的新输出替换 l_name 我希望它会有所帮助..