I want to replace a single character at a particular position in a string.
Example
String: 123-456-7890
Desired Output: 123-406-7890 (Replacing 5 at fifth position with 0)
I want to replace a single character at a particular position in a string.
Example
String: 123-456-7890
Desired Output: 123-406-7890 (Replacing 5 at fifth position with 0)
Use stringByReplacingCharactersInRange:withString:
, forming the NSRange
variable to indicate the 5th position.
NSString *phoneNumber = @"123-456-7890";
NSString *newString = [phoneNumber stringByReplacingCharactersInRange:NSMakeRange(5, 1) withString:@"0"];
NSLog(@"%@", newString);
Output: 123-406-7890
Read all about NSString.
for replacing string there are lots of way:
NSString *str = [yourString stringByReplacingOccuranceOfString:@"5" withString:@"0"];
second way first get range of string like:
NSRange range = [yourSting rangeOfString:@"5"];
NSString *first = [yourString substringToIndex:range.location];
NSString *second = [yourString substringFromIndex:range.location+range.length];
NSString *yourNewStr = [NSString stringWithFormat:@"%@0%@",first,second];
Tere are lots of other using string operation but First one is best in that.
If you want to actually replace the 5th character rather than just any 5 you need to make a range first.
NSRange range = NSMakeRange(5, 1);
NSString *newString = [initialString stringByReplacingCharactersInRange:range withString:@"0"];
Edit: Corrected make range length
you can use :-
NSString *replacechar = @"0";
NSString *newString= [String stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:replacechar];
Get the range (i.e. index) of first occurrence of the substring. Then replace at that range with your desired replace value.
NSString *originalString = @"123 456 789";
NSRange r = [originalString rangeOfString:@"5"];
NSString *newString = [originalString stringByReplacingCharactersInRange:r withString:@"0"];