String replacement in Objective-C

IosObjective CIphoneNsstring

Ios Problem Overview


How to replace a character is a string in Objective-C?

Ios Solutions


Solution 1 - Ios

You could use the method

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

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

Solution 2 - Ios

NSString objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString, that gives you several methods for replacing characters within a string. It's probably your best bet.

Solution 3 - Ios

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

Solution 4 - Ios

It also posible string replacement with stringByReplacingCharactersInRange:withString:

for (int i = 0; i < card.length - 4; i++) {
    
    if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
       
        NSRange range = NSMakeRange(i, 1);
        card = [card stringByReplacingCharactersInRange:range withString:@"*"];
        
    }
    
} //out: **** **** **** 1234

Solution 5 - Ios

The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:

first I check the iOS version:

if (![self compareCurVersionTo:4 minor:3 point:0])

Than:

// set RTL on the start on each line (except the first)  
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
                                                           withString:@"\u202B\n"];

Solution 6 - Ios

NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question4thSpaceView Question on Stackoverflow
Solution 1 - IosepatelView Answer on Stackoverflow
Solution 2 - IosmipadiView Answer on Stackoverflow
Solution 3 - Iostania_SView Answer on Stackoverflow
Solution 4 - IosMarlon RuizView Answer on Stackoverflow
Solution 5 - IosMeirView Answer on Stackoverflow
Solution 6 - IosShaik TamimView Answer on Stackoverflow