Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing one character in a string in Objective-C

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?

I know the location of the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?

like image 839
RanLearns Avatar asked Mar 07 '11 18:03

RanLearns


People also ask

How do you replace a character in a string in Objective C?

To replace a character in objective C we will have to use the inbuilt function of Objective C string library, which replaces occurrence of a string with some other string that we want to replace it with.

How do you replace a specific character in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you replace a value in a string?

replace() Return Value The replace() method returns a copy of the string where the old substring is replaced with the new substring. The original string is unchanged. If the old substring is not found, it returns the copy of the original string.

How do I remove special characters from a string in Objective C?

$string = preg_replace('/[^\da-z ]/i', '', $string);// Removes special chars. $string = str_replace(' ', '-', $string); // Replaces all spaces with underscore.


2 Answers

If it is always the same character you can use:

stringByReplacingOccurrencesOfString:withString: 

If it is the same string in the same location you can use:

stringByReplacingOccurrencesOfString:withString:options:range: 

If is just a specific location you can use:

stringByReplacingCharactersInRange:withString: 

Documentation here: https://developer.apple.com/documentation/foundation/nsstring

So for example:

NSString *someText = @"Goat"; NSRange range = NSMakeRange(0,1); NSString *newText = [someText stringByReplacingCharactersInRange:range withString:@"B"]; 

newText would equal "Boat"

like image 174
theChrisKent Avatar answered Sep 18 '22 18:09

theChrisKent


NSString *str = @"123*abc"; str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""]; //str now 123abc 
like image 31
MaxEcho Avatar answered Sep 19 '22 18:09

MaxEcho