NSString stringByReplacingPercentEscapesUsingEncoding not working

I need to get url string from NSString. I do the following:

NSString * str = [NSString stringWithString:@" i@gmail.com "]; NSString * eStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",eStr); 

The result is i@gmail.com. But I need i% 40gmail.com. replacing NSUTF8StringEncoding with NSASCIIStringEncoding does not help.

+6
source share
1 answer

You are using the wrong method. It does the opposite, the percentage transfer runs off to its characters. You probably want to use stringByAddingPercentEscapesUsingEncoding:

 NSString *str = @" i@gmail.com "; NSString *eStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

Also, it looks like the @ character is not escaped by default. Then, as stated in the documentation for the above method, you need to use CoreFoundation to achieve what you want.

 NSString *str = @" i@gmail.com "; CFStringRef eStr = CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, (CFStringRef)@"@", kCFStringEncodingUTF8 ); NSLog(@"%@", eStr); CFRelease(eStr); 

Please check the documentation to learn more about the function used and how to do it according to your needs.

+12
source

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


All Articles