Objective-C:如何提取字符串的一部分(例如以“#"开头) [英] Objective-C: How to extract part of a String (e.g. start with '#')
本文介绍了Objective-C:如何提取字符串的一部分(例如以“#"开头)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的字符串,
I have a string as shown below,
NSString * aString = @"This is the #substring1 and #subString2 I want";
如何仅选择以#"开头(并以空格结尾)的文本,在本例中为subString1"和subString2"?
How can I select only the text starting with '#' (and ends with a space), in this case 'subString1' and 'subString2'?
注意:为了清楚起见,对问题进行了编辑
Note: Question was edited for clarity
推荐答案
您可以使用 NSScanner 拆分字符串.这段代码将遍历一个字符串并用子字符串填充一个数组.
You can do this using an NSScanner to split the string up. This code will loop through a string and fill an array with substrings.
NSString * aString = @"This is the #substring1 and #subString2 I want";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before #
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:@"#" intoString:nil]; // Scan the # character
if([scanner scanUpToString:@" " intoString:&substring]) {
// If the space immediately followed the #, this will be skipped
[substrings addObject:substring];
}
[scanner scanUpToString:@"#" intoString:nil]; // Scan all characters before next #
}
// do something with substrings
[substrings release];
代码的工作原理如下:
- 最多扫描一个#.如果未找到,则扫描器将位于字符串的末尾.
- 如果扫描仪在字符串的末尾,我们就完成了.
- 扫描 # 字符,使其不在输出中.
- 最多扫描一个空格,扫描的字符存储在
substring
中.如果 # 是最后一个字符,或者后面紧跟一个空格,则该方法将返回 NO.否则返回YES. - 如果扫描了字符(方法返回YES),将
substring
添加到substrings
数组中. - 转到 1
- Scan up to a #. If it isn't found, the scanner will be at the end of the string.
- If the scanner is at the end of the string, we are done.
- Scan the # character so that it isn't in the output.
- Scan up to a space, with the characters that are scanned stored in
substring
. If either the # was the last character, or was immediately followed by a space, the method will return NO. Otherwise it will return YES. - If characters were scanned (the method returned YES), add
substring
to thesubstrings
array. - GOTO 1
这篇关于Objective-C:如何提取字符串的一部分(例如以“#"开头)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文