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?
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.
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.
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.
$string = preg_replace('/[^\da-z ]/i', '', $string);// Removes special chars. $string = str_replace(' ', '-', $string); // Replaces all spaces with underscore.
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"
NSString *str = @"123*abc"; str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""]; //str now 123abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With