NSString manipulation, replacement, tag

Discussion in 'iOS Programming' started by mraheel, Apr 18, 2010.

  1. mraheel macrumors regular

    Apr 18, 2009
    Hi guys,

    I wanted to know if theres a single method or way that will help me replace strings for specific characters.


    like MALE - M FEMALE - F CHILD - P

    The longer way out is this..
    [str stringByreplacingOccurencesOfString:@"MALE" withString:@"M"];
    [str stringByreplacingOccurencesOfString:@"FEMALE" withString:@"F"];
    [str stringByreplacingOccurencesOfString:@"CHILD" withString:@"P"];
    All the strings to be replaced are in an NSDictionary with Keys as strings to be replaced and value as the replaced string.

    THis is kinda complicated as the NSDictionary is pretty big.

    One suggestion is to loop through the NSDictionary for the key that matches in the main string. "THIS IS MALE DUDE". If it contains, then replace it.
    THis could be a long process of usage,

    Instead, i was thinking if i used a tag '$' like "THIS IS $MALE DUDE".
    THen i could do a local search of the string, if it contains $ then grab that word and replace it with 'M'. Is this a better way or makes no difference??
    Now the problem is, how do I grab the word if it starts with '$'.

    any helps appreciated guys
  2. ChOas macrumors regular

    Nov 24, 2006
    The Netherlands
    You could split your original string up in substrings, then looping over those to look them up in your dictionary, when found replace, leave as when not found.

    Then just append the result for each word (replaced, or not) to a new string.
  3. mraheel thread starter macrumors regular

    Apr 18, 2009
    That would require, splitting the whole string into an array and looping through that array and the NSDictionary to find a match,

    How does this sound instead?

    	NSString *mTitle = @"This is [Male] Dude";
    	NSRange startRange = [mTitle rangeOfString:@"["];
    	if(startRange.length >0){
    	NSRange endRange = [mTitle rangeOfString:@"]"];
    	NSRange search = NSMakeRange(startRange.location+1,endRange.location-startRange.location-1);
    		NSString *fTitle = [mTitle substringWithRange:search];
    		mTitle = [mTitle stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"[%@]",fTitle] withString:[Dictionary objectForKey:fTitle]];	
    Instead of splitting the string, I'm extracting any word between [ ]. Those brackets are an assurance that it has to be replaced and a theres a Key in dictionary, hence no searching, looping.

    I'm only searching the NSString this time,

    I'd like to know if this is a good option, cuz this has to go in
    -cellforRowAtIndexPath, and I wana know the best way to do so that the table doesnt lag when scrolled.

Share This Page