Replace " " character in an NSString with "\ " (to create a Unix path)

17,124

You should use @"\\ " instead of @"\ ". In C \ is the escape character. You need to escape it with another \.

Share:
17,124
Corey Floyd
Author by

Corey Floyd

An iPhone developer, now in Philly!

Updated on June 13, 2022

Comments

  • Corey Floyd
    Corey Floyd almost 2 years

    Using the following doesn't work:

    - (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
    

    By doesn't work I mean does not do any replacement what so ever. It returns the same exact string.

    Is there a convenience method to do this? Similar to:

    - (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
    

    My code (just one line):

    NSString *escapedPath = [pathToBeConverted stringByReplacingOccurrencesOfString:@" " 
                                                                         withString:@"\ "];
    

    Also, my compiler warning. Which likely has much to do with this:

    warning: unknown escape sequence: '\040'
    
  • Corey Floyd
    Corey Floyd over 14 years
    Thanks. that was dumb, I was dumping into an NSAppleScript, which was also escaped and I completely missed it.
  • Corey Floyd
    Corey Floyd over 14 years
    Yes, thanks. It is exactly what I need. I need to get rid of spaces in the file names
  • mmx
    mmx over 14 years
    Oh, got it. I was thinking you have a space delimited string and you want to construct a path name with it.