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];
以下是代码的工作方式:
Here is how the code works:
- 最多扫描#个.如果找不到,则扫描程序将位于字符串的末尾.
- 如果扫描仪位于字符串的末尾,则说明已完成.
- 扫描#字符,使其不在输出中.
- 扫描到一个空格,扫描的字符存储在
substring
中.如果#是最后一个字符,或者紧随其后是空格,则该方法将返回NO.否则它将返回是". - 如果已扫描字符(该方法返回YES),则将
substring
添加到substrings
数组中. - GOTO 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屋!
查看全文