Objective-C:如何提取字符串的一部分(例如以“#"开头) [英] Objective-C: How to extract part of a String (e.g. start with '#')

查看:36
本文介绍了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];

代码的工作原理如下:

  1. 最多扫描一个#.如果未找到,则扫描器将位于字符串的末尾.
  2. 如果扫描仪在字符串的末尾,我们就完成了.
  3. 扫描 # 字符,使其不在输出中.
  4. 最多扫描一个空格,扫描的字符存储在substring中.如果 # 是最后一个字符,或者后面紧跟一个空格,则该方法将返回 NO.否则返回YES.
  5. 如果扫描了字符(方法返回YES),将substring添加到substrings数组中.
  6. 转到 1
  1. Scan up to a #. If it isn't found, the scanner will be at the end of the string.
  2. If the scanner is at the end of the string, we are done.
  3. Scan the # character so that it isn't in the output.
  4. 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.
  5. If characters were scanned (the method returned YES), add substring to the substrings array.
  6. GOTO 1

这篇关于Objective-C:如何提取字符串的一部分(例如以“#"开头)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆