Replace \\ with \ using stringByReplacingOccurrencesOfString

I use code bump to replace \\ with \

NSString *str =@ "\\u597d\\u6f02\\u4eae\\u7684\\u5a5a"; str= [str stringByReplacingOccurrencesOfString: @"\\\\" withString: @"\\" ]; 

but it looks like stringByReplacingOccurrencesOfString is not working. Both of them output

  \u597d\u6f02\u4eae\u7684\u5a5a 

Welcome any comment

+4
source share
2 answers

This is because the source string does not contain double slashes: all duplicated slashes are consumed by the compiler when creating the string constant and are replaced by single slashes to get the final string:

 \u597d\u6f02\u4eae\u7684\u5a5a 

When you use a slash inside a string constant, two slashes are required to represent one slash. When you use a slash in a string constant that you pass into a regular expression, you need four slashes: two out of four will be consumed by the compiler, and then one of the remaining two will be consumed by the regex compiler.

Here is your example that does what you expected from it:

 NSString *str =@ "\\\\u597d\\\\u6f02\\\\u4eae\\\\u7684\\\\u5a5a"; NSLog(@"%@", str); str= [str stringByReplacingOccurrencesOfString: @"\\\\" withString: @"\\" ]; NSLog(@"%@", str); 

The result is as follows:

 \\u597d\\u6f02\\u4eae\\u7684\\u5a5a \u597d\u6f02\u4eae\u7684\u5a5a 
+4
source

In str there is no \\\\ in it - there is only \\ , as you can see ... This is what you print after the first assignment operator, so stringByReplacingOccurrencesOfString cannot find anything to replace.

0
source

Source: https://habr.com/ru/post/1411426/


All Articles