How can I select a string from the beginning until a specified character?

10,076
NSRange rangeOfDash = [someString rangeOfString:@"-"];
substring = (rangeOfDash.location != NSNotFound) ? [someString substringToIndex:rangeOfDash.location] : nil;

This sets the substring to nil if there's no dash in the someString.

Share:
10,076
Moshe
Author by

Moshe

iOS Engineer Website | GitHub | Careers | App Store

Updated on June 14, 2022

Comments

  • Moshe
    Moshe almost 2 years

    How can I select a string from the beginning until a specified character?

    For example, in the following a news headline...

    someString = @"Los Angeles, California - Apple announces something, stock prices change."

    How do I select just Los Angeles, California - into a separate string? (I want to base my selection on everything before the - ("dash") character.

    EDIT:

    Say my headline looks like this:

    someString = @"Los Angeles, California - Apple announces something - stock prices change."

    How do I prevent my location string from looking like this: Los Angeles, California - Apple announces something?

    Edit:

    My mistake, I was removing the first dash and then reprising the string. My mistake the posted answer works.

  • Moshe
    Moshe over 13 years
    What would rangeOfDash be based on someString after parsing the whole thing?
  • Moshe
    Moshe over 13 years
    I only want the first dash, not subsequent dashes. see my edit.