本文介绍了目标C:如何提取部分字符串(例如,以'#'开头)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  NSString * aString = @这是#substring1和#subString2 I想; 

如何只选择以'#'开头(以空格结尾)的文本,这种情况下'subString1'和'subString2'?



注意:为了清楚起见,编辑了问题

解决方案

您可以使用将字符串分开。

  NSString * aString = @这是#substring1和#subString2我想要; 
NSMutableArray * substrings = [NSMutableArray new];
NSScanner * scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:@#intoString:nil]; //扫描前面的所有字符#
while(![scanner isAtEnd]){
NSString * substring = nil;
[scanner scanString:@#intoString:nil]; //扫描#字符
if([scanner scanUpToString:@intoString:& substring]){
//如果紧跟在#后面的空格将被跳过
[子字符串addObject:substring];
}
[scanner scanUpToString:@#intoString:nil]; //在下一个#
之前扫描所有字符
//用子字符串做一些事
[substrings release];

以下是代码的工作原理:


  1. 扫描到#。如果找不到,扫描器将位于字符串的末尾。

  2. 如果扫描器位于字符串的末尾,我们就完成了。

  3. 扫描#字符,使其不在输出中。
  4. 扫描一个空格,扫描的字符存储在。如果#是最后一个字符,或者后面紧跟一个空格,则该方法将返回NO。
  5. 如果扫描了字符(方法返回YES),向 substring >子字符串数组。

  6. GOTO 1


I have a string as shown below,

NSString * aString = @"This is the #substring1 and #subString2 I want";

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

解决方案

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:

  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

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

08-21 07:02