Replace parts of text strings

Discussion in 'iOS Programming' started by newtoiphonesdk, Aug 3, 2012.

  1. newtoiphonesdk macrumors 6502a

    Jul 30, 2010
    In my app I have a plist of many quotes. These quotes are loaded into a UILabel, and has the option to share with Twitter. Some quotes are quite long, and I know I could easily cut all characters past the first 140, but I would like to include the name attributed to the quote at the end. Each quote is setup like this:
    "I just said something famous." - Me
    If the UILabel.text length is over 140 I would like to get the length, and subtract 140 from it, so I know how many characters must be removed. I have this part all setup in my code already. What I'm not for sure how to do is this:
    If the quote has 200 characters, find " -
    Then, remove the 63 characters immediately in front of " -
    Replace those 63 characters with ...
    This way a quote that looks like what I put above, if too long, would end up looking like:
    "I just said someth..." - Me

    I realize that there will be many occasions that it cuts a word off right in the middle, but I am willing to live with that. Any suggestions for removing a certain number of characters before the " - in the quote?
  2. NickFalk, Aug 3, 2012
    Last edited: Aug 4, 2012

    NickFalk macrumors 6502


    Jun 9, 2004
    If you are certain that the symbol - does not show up elsewhere in any of the quotes you could simply do this in a two step process.

    First separate the original string by using the componentsSeparatedByString: method. You should then have an array with two strings. The first one consisting of the actual quote and the second of the name. Then you can use the part of your quote that shortens the quote on the first string and output them however you like.

    Personally I would rework your method for shortening the quote as well. Rather than simply counting the letters you can separate the string by white space @" " thus ending up with an array of all the single words. Then use a mutable string and while loop structure to add each single word (+ a white space) from the array of words. Simply run the loop until the length of the mutable string + the next word in the array are larger than the 140 characters.

Share This Page