Basil Bourque
Basil Bourque

Reputation: 338775

Shortcut to generate an NSRange for entire length of NSString?

Is there a short way to say "entire string" rather than typing out:

NSMakeRange(0, myString.length)]

It seems silly that the longest part of this kind of code is the least important (because I usually want to search/replace within entire string)…

[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:NSMakeRange(0, myString.length)];

Upvotes: 73

Views: 39449

Answers (6)

vadian
vadian

Reputation: 285092

Swift 4+, useful for NSRegularExpression and NSAttributedString

extension String {
    var nsRange : NSRange {
        return NSRange(self.startIndex..., in: self)
    }

    func range(from nsRange: NSRange) -> Range<String.Index>? {
        return Range(nsRange, in: self)
    }
}

Upvotes: 30

Chris Conover
Chris Conover

Reputation: 9039

Swift 2:

extension String {
    var fullRange:Range<String.Index> { return startIndex..<endIndex }
}

as in

let swiftRange = "abc".fullRange

or

let nsRange = "abc".fullRange.toRange

Upvotes: 7

SwiftArchitect
SwiftArchitect

Reputation: 48514

Swift

NSMakeRange(0, str.length)

or as an extension:

extension NSString {
    func fullrange() -> NSRange {
        return NSMakeRange(0, self.length)
    }
}

Upvotes: 17

Odrakir
Odrakir

Reputation: 4254

This is not shorter, but... Oh well

NSRange range = [str rangeOfString:str];

Upvotes: 6

jscs
jscs

Reputation: 64002

Function? Category method?

- (NSRange)fullRange
{
    return (NSRange){0, [self length]};
}

[myString replaceOccurrencesOfString:@"replace_me"
                          withString:replacementString
                             options:NSCaseInsensitiveSearch
                               range:[myString fullRange]];

Upvotes: 47

BJ Homer
BJ Homer

Reputation: 49034

Not that I know of. But you could easily add an NSString category:

@interface NSString (MyRangeExtensions)
- (NSRange)fullRange
@end

@implementation NSString (MyRangeExtensions)
- (NSRange)fullRange {
  return (NSRange){0, self.length};
}

Upvotes: 20

Related Questions