Trim NSString: getting last occurrence of particular character?

Discussion in 'iOS Programming' started by Danneman101, Jul 26, 2010.

  1. Danneman101 macrumors 6502

    Aug 14, 2008
    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.
  2. robbieduncan Moderator emeritus


    Jul 24, 2002
  3. Danneman101 thread starter macrumors 6502

    Aug 14, 2008
    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.
  4. Danneman101 thread starter macrumors 6502

    Aug 14, 2008
    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
  5. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    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.
  6. dejo Moderator


    Staff Member

    Sep 2, 2004
    The Centennial State
    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.

Share This Page