-1

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)

6 Answers6

1

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/

visit here and read all about string

Saad
  • 8,857
  • 2
  • 41
  • 51
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.

greg
  • 4,843
  • 32
  • 47
0

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.

Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100
0

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

Ben Trengrove
  • 8,191
  • 3
  • 40
  • 58
0

you can use :-

NSString *replacechar = @"0";
NSString *newString= [String stringByReplacingCharactersInRange:NSMakeRange(5,1) withString:replacechar]; 
Abhishek Singh
  • 6,068
  • 1
  • 23
  • 25
0

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"];
Peter Kelly
  • 14,253
  • 6
  • 54
  • 63