如何截断NSString?

时间:2011-08-12 01:11:52

标签: iphone objective-c nsstring

我查看了字符串格式化文档,但无法确切知道如何执行此操作。

让我说我有这样的刺痛

@"(01–05) Operations on the nervous system"

我想从中创建2个字符串,如下所示:

@"01-05"@"Operations on the nervous system"

我该怎么做?

以下是我查看过的文档:http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

3 个答案:

答案 0 :(得分:2)

给它一个机会。它可能有点偏差,我还没检查过拼写错误。但是你现在可以搞定这个想法,你可以搞乱它。

NSString * sourceString = @"(01–05) Operations on the nervous system";

NSString *string1 = [sourceString substringToIndex:6];
string1 = [string1 stringByReplacingOccurrencesOfString:@"(" withString:@""];

//string1 = 01-05

NSString *string2 =[sourceString substringFromIndex:7];

//string2 = Operations on the nervous system

答案 1 :(得分:2)

如果您只想要字符“(”和“)”所包含的第一个子字符串以及之后的任何内容,我建议您执行以下操作:

NSString *original = @"(01–05) Operations on the nervous system";
NSString *firstPart = [NSString string];
NSString *secondPart = [NSString string];
NSScanner *scanner = [NSScanner scannerWithString:original];

[scanner scanUpToString:@"(" intoString:NULL];           // find first "("
if (![scanner isAtEnd]) {
    [scanner scanString:@"(" intoString:NULL];           // consume "("
    [scanner scanUpToString:@")" intoString:&firstPart]; // store characters up to the next ")"
    if (![scanner isAtEnd]) {
        [scanner scanString:@")" intoString:NULL];       // consume ")"

        // grab the rest of the string
        secondPart = [[scanner string] substringFromIndex:[scanner scanLocation]];
    }
}

当然,secondPart字符串仍然会有空格,并且在它的前面有什么空白,以摆脱那些你可以做的事情:

secondPart = [secondPart stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet];

使用NSScanner的优点是您不必对firstPart子字符串的开头和结尾进行硬编码。

答案 2 :(得分:1)

NSString * theFirstStringSubString = [NSString substringFromIndex:1];

NSString * theFirstStringSecondSubstring = [theFirstStringSubString substringToIndex:6];

现在theFirstStringSecondSubstring是01-05 对于另一个但在不同的索引处同样的事情。请注意,这些是自动释放的字符串。如果你想保留它们,请保留它。