user3647675
user3647675

Reputation:

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 i.e. after "."

Is there any API available for doing this?

Upvotes: 1

Views: 511

Answers (4)

Abizern
Abizern

Reputation: 150745

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

Playground example

Upvotes: 0

MedAmine.Rihane
MedAmine.Rihane

Reputation: 1223

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

Upvotes: 1

David Berry
David Berry

Reputation: 41246

Use rangeOfString and substringFromIndex:

let string = "123.45"
if let index = string.rangeOfString(".") {
    let cents = string.substringFromIndex(index.endIndex)
    print("\(cents)")
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

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

Upvotes: 5

Related Questions