简体   繁体   中英

How would I Find a Word, and Take all characters after the first occurrence of the word, but stop after an occurrence of a different word?

For instance

NSString *string = @"I need help finding a string";
NSString *newString = @"need";

I would need this to work not only to work for this string. An example would be to take a string and remove everything after the word "I " and before the word " help". Thank you very much!

Moved from a comment for legibility:

NSString *string = @"I need help finding a string";
NSRange rr2 = [TWEET rangeOfString:@"I "];
NSRange rr3 = [TWEET rangeOfString:@" help"];
int lengt = rr3.location - rr2.location;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
NSString *link;
link = [TWEET substringWithRange:aa];
NSLog(@"The link is %@", link);

One way would be to split the string into single words, and iterate through it, first searching for the first word, while adding every word to a new string until you found it and the searching for the second word and after you found that just add the remaining words.

This could look like this in code:

    NSString *myString = @"I need help finding a string";

    NSString *firstWord = @"need";

    NSString *secondWord = @"a";

    NSMutableString *newString = [NSMutableString stringWithString:@""];

    int index = 0;

    for (NSString *word in [myString componentsSeparatedByString:@" "]) {
        if(index == 0) {
            if([word isEqualToString:firstWord])
                index = 1;
            [newString appendFormat:@"%@ ", word];
        }
        else if(index == 1) {
            if([word isEqualToString:secondWord])
                index = 2;
        }
        else
            [newString appendFormat:@"%@ ", word];

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM