View Full Version : Trim NSString: getting last occurrence of particular character?

Jul 26, 2010, 07:53 AM
There are a couple of methods to get substrings from a string, but I cant figure out which to use to trim my string so that the last "_D4" is removed.

Example of original string:

Since each number after each letter does not have to consist of one digit, the string can be of various length, so using substringToIndex alone wont do.

I guess what I have to do is to first find the index of the last occurrence of "_". I just cant figure out which method to use to get that index.

Jul 26, 2010, 08:14 AM
I'd suggest in future you spend a little linger reading the documentation. It really is there to help.

I'd look at rangeOfCharacterFromSet:options: (http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/rangeOfCharacterFromSet:options:). The NSBackwardsSearch (http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/c_ref/NSBackwardsSearch) option will help.

Jul 26, 2010, 09:01 AM
I appreciate the help, and I always go for the docs first and had already read that particular method twice without understanding it fully. And I still dont get how to implement it.

I guess the docs make more sense if you've programmed in ObjC for a while, but to a ObjC-newbie like they are pretty unintelligible - but then again Im more accustomed to the simplicity of C# and find ObjC to be very different from any programming-language Ive ever programmed with :P I just wish there were some code-snippets included in the docs to help understanding it.

Jul 26, 2010, 10:30 AM
Finally, when I had decided to get creative instead and trim the string letter by letter using the length of it as index until the last letter was "_", a last attempt at getting the syntax right worked :)

NSString *tempstr = @"A1_B2_C3";
int *tempIndex = (int)([tempstr rangeOfString:@"_" options:NSBackwardsSearch].location);

I don't know how you cope with ObjC, but cudos to you for mastering this complex language :) Both Java and C# is a walk in the park compared to the intricacies of ObjC/Cocoa :P

Jul 26, 2010, 10:39 AM
range.location is an int, not an int*. Your code isn't going to work correctly as you show it. It should be able to work without that type cast.

Jul 26, 2010, 01:12 PM
I just wish there were some code-snippets included in the docs to help understanding it.
The docs (especially the class references; look near the very top) frequently also include links to related programming guide(s) where code-snippets are common.