views:

131

answers:

2

Hi,

I'm having an NSString like this:

music that rocks.mp3 e99a65fb

The problem is that between the filename (musicthatrocks.mp3) and the CRC32 checksum (e99a65fb) there could be many more spaces then one. How can I split the line into an array? I thought of using componentsSeparatedByString, but my problem is that the filename can also contain spaces.

Thanks in advance.

+2  A: 

If you're OK with regular expressions, you could do it that way. For example (using RegexKitLite):

NSString * fileName = [line stringByMatching:@"(.*)\\s" capture:1];

An explanation of the regex: (.*) This will match as many characters as it can, until it finds a space character. However, the capture is greedy, which means it's going to grab as many characters as it can before the last space character (in a nutshell).

Or you can use NSString methods to find the last occurrence of the space character and get a substring from the beginning of the line to the last space character.

Or you can split the string base on @" ", throw away the last object in the array, and then recombine the array with @" ".

Dave DeLong
zomfg omg thanks you so much it works! Awesome!!
Time Machine
oh, I used RegexKitLite :-)
Time Machine
A: 
  1. Use componentsSeparatedByString:.
  2. Get the lastObject, which is the CRC32.
  3. Use subarrayWithRange: to create a new array without the CRC32.
  4. Use componentsJoinedByString: to reconstitute the filename.

You may want to do step 4 in a loop, repeatedly deleting the last object until either the filename exists in the target directory or you run out of empty strings at the end of the array. This handles the case of multiple spaces between filename and CRC32, as well as the case of a filename ending in spaces (pathological but possible).

Peter Hosey