查找 NSString 中子字符串的所有位置(不仅仅是第一个)
有一个子串在字符串中出现多次。我使用rangeOfString
,但似乎只能找到第一个位置。如何找到子字符串的所有位置?
NSString *subString1 = @"</content>";
NSString *subString2 = @"--\n";
NSRange range1 = [newresults rangeOfString:subString1];
NSRange range2 = [newresults rangeOfString:subString2];
int location1 = range1.location;
int location2 = range2.location;
NSLog(@"%i",location1);
NSLog(@"%i",location2);
There is a substring that occurs in a string several times. I use rangeOfString
, but it seems that it can only find the first location. How can I find all the locations of the substring?
NSString *subString1 = @"</content>";
NSString *subString2 = @"--\n";
NSRange range1 = [newresults rangeOfString:subString1];
NSRange range2 = [newresults rangeOfString:subString2];
int location1 = range1.location;
int location2 = range2.location;
NSLog(@"%i",location1);
NSLog(@"%i",location2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
rangeOfString:options:range:
并将第三个参数设置为超出第一次出现的范围。例如,您可以执行以下操作:You can use
rangeOfString:options:range:
and set the third argument to be beyond the range of the first occurrence. For example, you can do something like this:Swift 3.0
查找子字符串
i
的所有位置,并输出 -
Swift 3.0
Find all locations of substring
i
And this output-
这是我的解决方案。基本上,该算法遍历字符串查找子字符串匹配项并在数组中返回这些匹配项。
由于 NSRange 是一个结构体,因此不能直接添加到数组中。通过使用 NSValue,我可以先对匹配项进行编码,然后将其添加到数组中。为了检索范围,我将 NSValue 对象解码为 NSRange。
This is my solution. Basically, the algorithm traverses the string looking for substring matches and returns those matches in an array.
Since an NSRange is a struct it cannot be added to the array directly. By using NSValue, I can encode the match first and then add it to the array. To retrieve the range, I then decode the NSValue object to an NSRange.
将 nil 传递给 [string rangeOfString:substring options:nil range:searchRange]; 显示警告。
要消除警告,请放入该组中的枚举
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/doc/constant_group/Search_and_Comparison_Options
Passing nil to [string rangeOfString:substring options:nil range:searchRange]; shows a warning.
To get rid of the warning, put in an enum from this group
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/doc/constant_group/Search_and_Comparison_Options
这是 PengOne 答案的 Swift 2.2 版本,输入来自 kevinlawler 和 Gibtang
注意:字符串和子字符串的类型为 NSString
Here is a version in Swift 2.2 of PengOne's answer with input from kevinlawler and Gibtang
Note: string and substring are of type NSString
我建议使用正则表达式,因为它是一种更具声明性的方式,并且需要编写的代码行更少。
I suggest using regular expression because it's a more declarative way and has fewer lines of code to write.
迅捷版
Swift version