2

In objective-c I want to replace the string "AB\(cd" to "AB\\(cd". This is what I have tried

NSMutableString * str = @"AB\(cd";
NSString * replace = @"\\(";
[str stringByReplacingOccurrencesOfString:@"\("
                                       withString:replace];

NSLog(@"%@",str);

Result is "AB(cd" but I want it as "AB\\\(cd"

Please can somebody help me on this

6
  • @Popeye, I believe you have changed the total meaning of the question with the edit. Commented Sep 24, 2014 at 14:57
  • @user1190882 In what way? You can't replace a string using iOS you use code (In this case Objective-c) to replace the string so I have replaced this correctly Commented Sep 24, 2014 at 14:58
  • The code to this question doesn't make sense as it is stringByReplacingOccurrencesOfString:withString: returns a string and you don't pass it into str so str should remain as "AB\(cd" when NSLogging it. Commented Sep 24, 2014 at 14:59
  • Not to mention that the compiler won't like \( in the string literal. Commented Sep 24, 2014 at 15:00
  • @Popeye, in beginning, I can see it as "AB\\(CD", and ending I can see it as "AB\\\(CD" Commented Sep 24, 2014 at 15:06

1 Answer 1

2

You forgot to assign the return value from [NSString stringByReplacingOccurrencesOfString:withString:]:

NSString *replaced = [str stringByReplacingOccurrencesOfString:@"\\("
                                                    withString:@"\\\\("];

However if you want to replace the original str then you need to re-assign it with a mutable copy as it's an NSMutableString:

str = [str stringByReplacingOccurrencesOfString:@"\\("
                                     withString:@"\\\\("] mutableCopy];
Sign up to request clarification or add additional context in comments.

4 Comments

i want it to come as AB doublebackward slash (cd
@user3115014 Yeah that's what the code in my answer should do.
if iam putting that in stackoverflow its triming one slash
@user3115014 Ah I see; I've fixed the code in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.