问题
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)];
回答1:
Function? Category method?
- (NSRange)fullRange
{
return (NSRange){0, [self length]};
}
[myString replaceOccurrencesOfString:@"replace_me"
withString:replacementString
options:NSCaseInsensitiveSearch
range:[myString fullRange]];
回答2:
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};
}
回答3:
Swift
NSMakeRange(0, str.length)
or as an extension:
extension NSString {
func fullrange() -> NSRange {
return NSMakeRange(0, self.length)
}
}
回答4:
This is not shorter, but... Oh well
NSRange range = [str rangeOfString:str];
回答5:
Swift 4+, useful for NSRegularExpression and NSAttributedString
extension String {
var nsRange : NSRange {
return NSRange(self.startIndex..., in: self)
}
}
回答6:
Swift 2:
extension String {
var fullRange:Range<String.Index> { return startIndex..<endIndex }
}
as in
let swiftRange = "abc".fullRange
or
let nsRange = "abc".fullRange.toRange
来源:https://stackoverflow.com/questions/15062458/shortcut-to-generate-an-nsrange-for-entire-length-of-nsstring