Objective-C 中的 NSString indexOf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/256460/
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
NSString indexOf in Objective-C
提问by Guido
Is there anything similar to an indexOffunction in the NSString objects?
有没有类似于indexOfNSString 对象中的函数的东西?
回答by Airsource Ltd
Use -[NSString rangeOfString:]:
使用-[NSString rangeOfString:]:
- (NSRange)rangeOfString:(NSString *)aString;
Finds and returns the range of the first occurrence of a given string within the receiver.
查找并返回给定字符串在接收器中第一次出现的范围。
回答by orafaelreis
If you want just know when String a contains String b use my way to do this.
如果您只想知道 String a 何时包含 String b,请使用我的方法来执行此操作。
#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)
//using
NSString a = @"PUC MINAS - BRAZIL";
NSString b = @"BRAZIL";
if( contains(a,b) ){
//TO DO HERE
}
This is less readable but improves performance
这不太可读,但提高了性能
回答by firestoke
I wrote a category to extend original NSString object. Maybe you guys can reference it. (You also can see the articlein my blog too.)
我写了一个类别来扩展原始 NSString 对象。或许大家可以参考一下。(你也可以在我的博客中看到这篇文章。)
ExtendNSString.h:
扩展NSString.h:
#import <Foundation/Foundation.h>
@interface NSString (util)
- (int) indexOf:(NSString *)text;
@end
ExtendNSStriing.m:
扩展NSString.m:
#import "ExtendNSString.h"
@implementation NSString (util)
- (int) indexOf:(NSString *)text {
NSRange range = [self rangeOfString:text];
if ( range.length > 0 ) {
return range.location;
} else {
return -1;
}
}
@end
回答by William Falcon
I know it's late, but I added a category that implements this method and many others similar to javascript string methods
https://github.com/williamFalcon/WF-iOS-Categories
我知道已经晚了,但我添加了一个实现此方法的类别以及许多其他类似于 javascript 字符串方法的类别
https://github.com/williamFalcon/WF-iOS-Categories

