2012-03-08 10 views

Respuesta

12

¿Qué tal

// 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)]; 
} 

O simplemente

[sourceString stringByReplacingOccurrencesOfString:searchString withString:targetString]; 

si desea cambiar el searchString que en el mismo valor en todas partes de la cadena de origen.

+0

También usando: NSArray * stringArray = [myString componentsSeparatedByString: @ "mySubString"]; –

+0

Toqué la tecla incorrecta y mi respuesta se envió incompleta al principio :-) – TheEye

+2

Por componentesSeparado ... elimina todas las apariciones de su cadena de búsqueda, no itera sobre ellas ... – TheEye

6

Me gustaría ir con algo como esto:

// 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); 
+0

eso es complicado, hay una método para eso: '- (void) enumerateSubstringsInRange: (NSRange) opciones de rango: (NSStringEnumerationOptions) opta usarBlock: (void (^) (NSString * subserie, NSRange substringRange, NSRange enclosingRange, BOOL * stop)) block'. – calimarkus

+0

Eso, es un muy buen punto. +1 en tu respuesta para eso. – mattjgalloway

+0

Muy útil después de buscar mucho. Gracias. +1 –

1

Es posible que desee echar un vistazo a NSString class Documentation.

encontrar de caracteres y subcadenas

– rangeOfCharacterFromSet: 
– rangeOfCharacterFromSet:options: 
– rangeOfCharacterFromSet:options:range: 
– rangeOfString: 
– rangeOfString:options: 
– rangeOfString:options:range: 
– rangeOfString:options:range:locale: 
– enumerateLinesUsingBlock: 
– enumerateSubstringsInRange:options:usingBlock: 

La división de cadenas

– componentsSeparatedByString: 
– componentsSeparatedByCharactersInSet: 
– stringByTrimmingCharactersInSet: 
– substringFromIndex: 
– substringWithRange: 
– substringToIndex: 
5

Si usted quiere hacer cambios, se puede utilizar:

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

pero si eso no se ajusta a sus necesidades intente esto:

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

+0

Ver la documentación, según lo observado por HelmiB. – calimarkus

0

Ampliando @ theeye de answer, cociné esto:

@interface NSString (EnumerateOccurancesOfString) 

- (void)enumerateOccurancesOfString:(NSString *)string usingBlock:(void (^)(NSRange substringRange, BOOL *stop))block; 

@end 

-

@implementation NSString (EnumerateOccurancesOfString) 

- (void)enumerateOccurancesOfString:(NSString *)string usingBlock:(void (^)(NSRange range, BOOL * _Nonnull stop))block { 

    NSParameterAssert(block); 

    NSRange range = [self localizedStandardRangeOfString:string]; 

    if (range.location == NSNotFound) return; 


    // Iterate all occurances of 'string' 
    while (range.location != NSNotFound) 
    { 
     BOOL stop = NO; 

     block(range, &stop); 

     if (stop) { 
      break; 
     } 

     // Continue the iteration 
     NSRange nextRange = NSMakeRange(range.location + 1, self.length - range.location - 1); 
     range = [self rangeOfString:string options:(NSStringCompareOptions)0 range:nextRange locale:[NSLocale currentLocale]]; // Will this sometimes conflict with the initial range obtained with -localizedStandardRangeOfString:? 
    } 
} 

@end