I often save files from my iPhone app to a Windows PC. While under iOS you might use some characters, in a Windows system you can't.
So I built this Objective-C function to help me manage the not-safe chars.
/** Trim all character that are not allowed or not safe on Windows filesystem.
This function keeps only "a-z", "A-Z", "0-9", "space", "-" and "_" characters.
It also deletes empty spaces at the beginning and end of the name.
In addition, no dots are allowed at the end of the name.
@param str Original string.
@return Returns a Windows-safe string.
*/
+ (NSString *)trimCharactersNotAllowedOnWindowsFileSystemFromString:(NSString *)str {
// This will turn, for example, é (U+00E9) into e’ (U+0065 U+0301).
str = [str decomposedStringWithCanonicalMapping];
NSMutableString *stripped = [NSMutableString stringWithCapacity:str.length];
for (NSInteger i=0; i<str.length; i++) {
unichar c = [str characterAtIndex:i];
// Only allow a-z, A-Z, 0-9, space, -, _
if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ' ' || c == '-' || c == '_' ) {
[stripped appendFormat:@"%c", c];
}
}
// No empty spaces at the beginning or end of the path name (also no dots at the end).
return [stripped stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
Download the ready-for-use source file (.m) of Delete not allowed chars for filesystem
No comments:
Post a Comment