如何从开头到指定字符选择字符串?

时间:2022-12-31 14:12:24

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."

someString = @“洛杉矶,加利福尼亚 - 苹果宣布了一些事情,股价发生变化。”

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."

someString = @“洛杉矶,加利福尼亚 - 苹果宣布了一些事情 - 股价变动。”

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

如何防止我的位置字符串看起来像这样:洛杉矶,加利福尼亚 - Apple宣布了什么?

Edit:

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

我的错误,我正在删除第一个破折号,然后重新发现字符串。我的错误是发布的答案有效。

1 个解决方案

#1


23  

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.

这台子为零,如果有在someString没有冲刺。

#1


23  

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.

这台子为零,如果有在someString没有冲刺。