简体   繁体   中英

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.

Here is my requirement, Given Amount = "144.44" Need NSRange of only cent part ie after "."

Is there any API available for doing this?

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

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 :

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

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!)

操场上的例子

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