Trim NSString: getting last occurrence of particular character?

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

  1. macrumors 6502

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

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
  3. thread starter macrumors 6502

    Joined:
    Aug 14, 2008
    #3
    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. thread starter macrumors 6502

    Joined:
    Aug 14, 2008
    #4
    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
     
  5. macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #5
    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. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    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