Objective-C String-Replace

I want to replace several elements in my line in Objective-C.

In PHP you can do this:

str_replace(array("itemtoreplace", "anotheritemtoreplace", "yetanotheritemtoreplace"), "replacedValue", $string);

However, in objective-c, the only method I know of is NSString replaceOccurancesOfString. Is there an efficient way to replace multiple lines?

This is my current solution (very inefficient and ... well ... long)

NSString *newTitle = [[[itemTitleField.text stringByReplacingOccurrencesOfString:@"'" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@"'"] stringByReplacingOccurrencesOfString:@"^" withString:@""];

See what I mean?

Thanks Christian Stewart

+3
source share
4 answers

, , , , /. , , - :

// Original String
NSString *originalString = @"My^ mother^ told me not to go' outside' to' play today. Why did I not listen to her?";

// Method Start
// MutableArray of String-pairs Arrays
NSMutableArray *arrayOfStringsToReplace = [NSMutableArray arrayWithObjects:
                                           [NSArray arrayWithObjects:@"'",@"",nil], 
                                           [NSArray arrayWithObjects:@" ",@"'",nil], 
                                           [NSArray arrayWithObjects:@"^",@"",nil], 
                                           nil];

// For or while loop to Find and Replace strings
while ([arrayOfStringsToReplace count] >= 1) {
    originalString = [originalString stringByReplacingOccurrencesOfString:[[arrayOfStringsToReplace objectAtIndex:0] objectAtIndex:0]
                                              withString:[[arrayOfStringsToReplace objectAtIndex:0] objectAtIndex:1]];
    [arrayOfStringsToReplace removeObjectAtIndex:0];
}

// Method End

:

2010-08-29 19:03:15.127 StackOverflow[1214:a0f] My'mother'told'me'not'to'go'outside'to'play'today.'Why'did'I'not'listen'to'her?
+12

Cocoa. , , , , , , . , .

, - , , . .:)

+2

Do you find your own method? Label the line and repeat its replacement one at a time, but instead of replacing the words in the line, there is no faster way than O (n).

No more than one cycle per cycle.

0
source

Add @ to the beginning of all lines, as in

withString:@""

He is out for a few.

-2
source

Source: https://habr.com/ru/post/1762202/


All Articles