Iphone迭代NSString的子字符串出现

Lui*_*cía 6 iphone nsstring

我想在NSString中找到所有出现的子字符串,并逐个迭代以对该NSString进行一些更改.我该怎么办?

The*_*Eye 12

怎么样

// find first occurrence of search string in source string
NSRange range = [sourceString rangeOfString:@"searchString"];
while(range.location != NSNotFound)
{
    // build a new string with your changed values

    range = [sourceString rangeOfString:@"searchString" options:0 range:NSMakeRange(range.location + 1, [sourceString length] - range.location - 1)];
}
Run Code Online (Sandbox Code Playgroud)

要不就

[sourceString stringByReplacingOccurrencesOfString:searchString withString:targetString];
Run Code Online (Sandbox Code Playgroud)

如果要将searchString更改为源字符串中的任何位置的相同值.

  • 通过componentsSeparated ...你删除所有出现的搜索字符串,你不会迭代它们... (2认同)

mat*_*way 7

我会用这样的东西:

// Setup what you're searching and what you want to find
NSString *string = @"abcabcabcabc";
NSString *toFind = @"abc";

// Initialise the searching range to the whole string
NSRange searchRange = NSMakeRange(0, [string length]);
do {
    // Search for next occurrence
    NSRange range = [string rangeOfString:toFind options:0 range:searchRange];
    if (range.location != NSNotFound) {
        // If found, range contains the range of the current iteration

        // NOW DO SOMETHING WITH THE STRING / RANGE

        // Reset search range for next attempt to start after the current found range
        searchRange.location = range.location + range.length;
        searchRange.length = [string length] - searchRange.location;
    } else {
        // If we didn't find it, we have no more occurrences
        break;
    }
} while (1);
Run Code Online (Sandbox Code Playgroud)


cal*_*kus 5

如果要进行更改,可以使用:

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

但如果这不符合您的需求,请尝试以下方法:

- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block