假设我有以下句子:
I am a sentence that has hyphenated-words at some-points in it.
我有以下代码:
NSCharacterSet *separators = [NSCharacterSet characterSetWithCharactersInString:@" -"];
NSArray *sentenceArray = [sentence componentsSeparatedByCharactersInSet:separators];
将字符串分隔成一个数组,以空格和连字符分隔。结果数组是:
["I", "am", "a", "sentence", "that", "has", "hyphenated", "words", "at", "some", "points", "in", "it."]
正如您所见,它完成了它的工作,但现在我不知道哪些词最初被连字符了。我真正喜欢的是
[ ... "has-", "hyphenated", ... ]
它在第一个字符串后附加分隔符。但仅适用于连字符。
但我意识到这似乎很难。我怎样才能最好地找出哪些部分因连字而分开?
最佳答案
像这样用 '- '
替换 '-'
怎么样:
NSCharacterSet *separators = [NSCharacterSet characterSetWithCharactersInString:@" "];
sentence = [sentence stringByReplacingOccurrencesOfString:@"-" withString:@"- "];
NSArray *sentenceArray = [sentence componentsSeparatedByCharactersInSet: separators];
关于ios - 我将如何最好地使用 componentsSeparatedByCharacterSet 但将分隔符/分隔符附加到第一个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367319/