Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

ios - Objective-C: How to extract part of a String (e.g. start with '#')

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...