5

将字符串分成两部分的最有效方法是什么,如下所示

一部分是字符串中最后一个空格字符之后的字符串的最后一个单词 第二部分是字符串的其余部分

例如“这是一个句子” 一部分:“句子” 第二部分:“这是一个” //注意这个字符串的末尾有空格

“这是一个”部分:“”第二部分:“这是一个”

4

3 回答 3

18

尝试这样的事情:

NSString *str = @"this is a sentence";

// Search from back to get the last space character
NSRange range = [str rangeOfString: @" " options: NSBackwardsSearch];

// Take the first substring: from 0 to the space character
NSString *str1 = [str substringToIndex: range.location]; // @"this is a" 

// take the second substring: from after the space to the end of the string
NSString *str2 = [str substringFromIndex: range.location +1];  // @"sentence"
于 2013-01-08T01:35:08.313 回答
6

从语义上讲,您是要删除最后一个单词,还是要在最后一个空格字符之后将所有内容都砍掉,这就是您所描述的?我问是因为它们实际上不是一回事,具体取决于文本的语言。

如果您想在最后一点空格之后切掉所有内容,那么这里的其他答案会很好。但是如果你想砍掉最后一个词,那么你需要更深入地挖掘并使用单词枚举API:

NSString *removeLastWord(NSString *str) {
    __block NSRange lastWordRange = NSMakeRange([str length], 0);
    NSStringEnumerationOptions opts = NSStringEnumerationByWords | NSStringEnumerationReverse | NSStringEnumerationSubstringNotRequired;
    [str enumerateSubstringsInRange:NSMakeRange(0, [str length]) options:opts usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        lastWordRange = substringRange;
        *stop = YES;
    }];
    return [str substringToIndex:lastWordRange.location];
}
于 2013-01-08T01:42:20.390 回答
2

您可以使用-[NSString componentsSeparatedByString:]and-[NSArray componentsJoinedByString:]将字符串拆分为单独的组件(单词)并再次拆分:

NSString *sentence = @"This is a sentence";
NSLog(@"Sentence: \"%@\"", sentence);
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
sentence = [sentence stringByTrimmingCharactersInSet:whitespace];

NSMutableArray *words = [[sentence componentsSeparatedByCharactersInSet:whitespace] mutableCopy];
NSString *lastWord = [words lastObject];
[words removeLastObject];
NSString *firstPart = [words componentsJoinedByString:@" "];

NSLog(@"Last word: \"%@\" First part: \"%@\"", lastWord, firstPart);

输出:

2013-01-07 18:36:50.566 LastWord[42999:707] Sentence: "This is a sentence"
2013-01-07 18:36:50.569 LastWord[42999:707] Last word: "sentence" First part: "This is a"

此代码假定需要注意一些事项。首先,它会修剪您在句子开头/结尾提到的空格,但不会保留它。因此,如果该空白对您而言实际上很重要,则您必须考虑到这一点。此外,如果句子为空或仅包含一个单词,它不会做任何特别的事情(这种方式很安全,只是不是特别复杂)。

于 2013-01-08T01:34:26.767 回答