NSString & lines.

Discussion in 'Mac Programming' started by netytan, Jan 14, 2005.

  1. macrumors 6502

    netytan

    Joined:
    May 23, 2004
    #1
    Hi again guys,

    I'm looking for a way to either iterate over each line in an NSString or to to count the number of lines in an NSString so that I can iterate over them ;). If anyone could point me in the right direction it would be much appreciated!

    Also, is there a way to strip unwanted characters from the start/end of a line: like chomp in perl or strip() in Python.

    Thanks in advance,

    Mark.
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Take a look at the NSString documentation on XCode. The - (NSArray *)componentsSeparatedByString:(NSString *)separator looks promising (@"\n" would be the separator)

    - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set can be used like chomp.
     
  3. thread starter macrumors 6502

    netytan

    Joined:
    May 23, 2004
    #3
    Thanks Robbie, the stringByTrimmingCharactersInSet: method was just what I was looking for :).

    I'm not so sure about the line separation because the approach doesn't seem unicode compatible (I could be wrong).

    Code:
    [i]From the docs on [b]"getLineStart:end:contentsEnd:forRange:"[/b][/i]
    A line is delimited by any of these characters, the longest possible sequence being preferred to any shorter:
    
    U+000D (\r or CR)
    
    U+2028 (Unicode line separator)
    
    U+000A (\n or LF)
    
    U+2029 (Unicode paragraph separator)
    
    \r\n, in that order (also known as CRLF)
    
    Maybe someone could answer this: in a unicode string, is the line terminator still "\n" or some other character? The string I'm working with is from an NSTextView if that helps.

    Thanks again :),

    Mark.
     
  4. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    Seems to be a fair point. Create some sort of recursive method to loop over separating by each possible line end character in turn?
     
  5. macrumors member

    northen

    Joined:
    Jan 8, 2005
    Location:
    Aalborg, Denmark
    #5
    I wrote a C library to do something like that, available at

    http://savannah.nongnu.org/projects/velocity/

    It's a bit stubby right now, but it will eventually have a VCount method. I haven't worked on it for a bit, though :p
     

Share This Page