2012-05-24 15 views

risposta

72
NSString *[email protected]"1,2,3,4"; 
[str stringByReplacingOccurrencesOfString:@"3," withString:@""]; 

che rimuoverà tutte le occorrenze di @ "3", in str.

Se si desidera rimuovere solo la prima occorrenza di @ "3":

NSString* str = @"1,2,3,4"; 
NSRange replaceRange = [str rangeOfString:@"3,"]; 
if (replaceRange.location != NSNotFound){ 
    NSString* result = [str stringByReplacingCharactersInRange:replaceRange withString:@""]; 
} 

Spero che questo aiuti.

+1

[str StringByReplacingOccurrencesOfString: @ "3," withString: @ ""]; – samfisher

+0

@samfisher modificato, grazie – sonxurxo

+2

Questo funzionerà solo se sapete che l'elemento da rimuovere è parzialmente l'elenco. Ad esempio, se il numero 4 dovesse essere rimosso, dovresti sapere che è alla fine della lista e che non esiste una virgola finale, quindi sostituisci "4" con "" piuttosto che "4". –

6
NSString *[email protected]"1,2,3,4"; 
    int numberToRemove = 4; 

str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%d",numberToRemove] withString:@""]; 
str = [str stringByReplacingOccurrencesOfString:@",," withString:@","]; 

Questo aiuterà.

+2

Questo risolve il problema che ho commentato alla risposta di @sonxurxo. –

Problemi correlati