Itzik984
Itzik984

Reputation: 16794

Objective C: Replace double backslash with a single backslash

I'm trying to replace a string that holds double backslash to a string with only single backslash, for example:

\\This\\Is\\Not\\Working

To:

\This\Is\Not\Working

Using:

str = [str stringByReplacingOccurrencesOfString:@"\\\\" withString@"\\"];

But for some reason, The string remains the same (with the double backslash) every single time. What am i doing wrong here?

Upvotes: 0

Views: 1382

Answers (4)

Itzik984
Itzik984

Reputation: 16794

Sadly, I misinterpreted the console log output. the string was fine, the debugger just showed the single slash as a doubled one. (For escaping purposes i'd imagine).

Upvotes: 1

Yahya Ibrahim
Yahya Ibrahim

Reputation: 251

Try this:

NSString *str = @"\\This\\Is\\Not\\Working";
str = [str stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
NSLog(@"%@", [str stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"]);
  • 1st Line is your user input.
  • 2nd Line converts the double back-slashed user input string into four back-slashed string
  • 3rd line simply replaces four back slashes with two back slashes which results in printing single back slash

Upvotes: 0

Chirag D jinjuwadiya
Chirag D jinjuwadiya

Reputation: 643

NSString *Str = @"\\This\\Is\\Not\\Working";
NSLog(@"%@",Str);// print:-\This\Is\Not\Working
Str = [Str stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];// in this no replace occurres
NSLog(@"%@",Str); // print:-\This\Is\Not\Working

NSString *Str1 = @"\\\\This\\\\Is\\\\Not\\\\Working";
NSLog(@"%@",Str1);// print:-\\This\\Is\\Not\\Working
Str1 = [Str1 stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSLog(@"%@",Str1);// print:-\This\Is\Not\Working

Upvotes: 0

Ronak Chaniyara
Ronak Chaniyara

Reputation: 5436

The below lines of code is fine:

NSString *str=@"\\This\\Is\\Not\\Working";

str = [str stringByReplacingOccurrencesOfString:@"\\\\" withString@"\\"];

Just check value by NSLog or by printing, because in debug console slash is represented as double slash.

Check image for more clear understanding:

enter image description here

Upvotes: 0

Related Questions