iOS Trim NSString: getting last occurrence of particular character?

Danneman101

macrumors 6502
Original poster
Aug 14, 2008
361
1
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:
"A1_B2_C3_D4"

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.
 

Danneman101

macrumors 6502
Original poster
Aug 14, 2008
361
1
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.
 

Danneman101

macrumors 6502
Original poster
Aug 14, 2008
361
1
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 :)

Code:
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
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
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.