[英]How to take NSRange in swift?
I am very much new to swift language. 我对快速语言非常陌生。 I am performing some business logic which needs to take
NSRange
from given String. 我正在执行一些业务逻辑,需要从给定的String中获取
NSRange
。
Here is my requirement, Given Amount = "144.44" Need NSRange
of only cent part ie after "." 这是我的要求,给定的金额=“
NSRange
”仅需要NSRange
的一部分,即“”之后。
Is there any API available for doing this? 有没有可用的API来执行此操作?
You can do a regex-based search to find the range: 您可以进行基于正则表达式的搜索来找到范围:
let str : NSString = "123.45"
let rng : NSRange = str.range("(?<=[.])\\d*$", options: .RegularExpressionSearch)
Regular expression "(?<=[.])\\\\d*$"
means "zero or more digits following a dot character '.'
正则表达式
"(?<=[.])\\\\d*$"
表示“在点字符'.'
之后的零个或多个数字'.'
via look-behind, all the way to the end of the string $
." 一直到字符串
$
的末尾。”
If you want a substring
from a given string
you can use componentsSeparatedByString
如果
substring
定string
的substring
string
,可以使用componentsSeparatedByString
Example : 范例:
var number: String = "144.44";
var numberresult= number.componentsSeparatedByString(".")
then you can get components as : 那么您可以将组件获取为:
var num1: String = numberresult [0]
var num2: String = numberresult [1]
hope it help !! 希望对你有帮助!
Use rangeOfString
and substringFromIndex
: 使用
rangeOfString
和substringFromIndex
:
let string = "123.45"
if let index = string.rangeOfString(".") {
let cents = string.substringFromIndex(index.endIndex)
print("\(cents)")
}
Another version that uses Swift Ranges, rather than NSRange 使用Swift Ranges而不是NSRange的另一个版本
Define the function that returns an optional Range: 定义返回可选范围的函数:
func centsRangeFromString(str: String) -> Range<String.Index>? {
let characters = str.characters
guard let dotIndex = characters.indexOf(".") else { return nil }
return Range(dotIndex.successor() ..< characters.endIndex)
}
Which you can test with: 您可以使用以下方法进行测试:
let r = centsRangeFromString(str)
// I don't recommend force unwrapping here, but this is just an example.
let cents = str.substringWithRange(r!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.