ios 为 NSString 的整个长度生成 NSRange 的快捷方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15062458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:25:40  来源:igfitidea点击:

Shortcut to generate an NSRange for entire length of NSString?

iosobjective-cnsstringnsrange

提问by Basil Bourque

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)];

采纳答案by jscs

Function? Category method?

功能?分类方法?

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


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

回答by BJ Homer

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

从来没听说过。但是您可以轻松添加一个NSString类别:

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

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

回答by SwiftArchitect

Swift

迅速

NSMakeRange(0, str.length)

or as an extension:

或作为extension

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

回答by vadian

Swift 4+, useful for NSRegularExpressionand NSAttributedString

Swift 4+,适用于NSRegularExpressionNSAttributedString

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

回答by Odrakir

This is not shorter, but... Oh well

这不是更短,而是......哦,好吧

NSRange range = [str rangeOfString:str];

回答by Chris Conover

Swift 2:

斯威夫特 2:

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

as in

let swiftRange = "abc".fullRange

or

或者

let nsRange = "abc".fullRange.toRange