开发者

How to truncate NSString?

I looked at the string formatting documents but couldn't figure out exactly how to do this.

Lets say I have a sting like this

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

I want to create 2 strings from this like so:

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

How can I do this?

Here are the docs I开发者_Python百科 looked at: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/FormatStrings.html


Give this a shot. It might be off a bit, I havent checked for typos. But you can mess around with it now that you get the idea.

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


If you just want the first substring contained by the characters "(" and ")" and anything after that I'd recommend doing something like this:

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]];
    }
}

Of course the secondPart string will still have spaces and whatnot at the front of it, to get rid of those you can do something along the lines of:

secondPart = [secondPart stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet];

The advantage of using NSScanner is that you don't have to hard-code the start and end of the firstPart substring.


NSString *theFirstStringSubString = [NSString substringFromIndex:1];

NSString *theFirstStringSecondSubstring = [theFirstStringSubString substringToIndex:6];

Now theFirstStringSecondSubstring is 01-05 same thing for the other but at different indexes. Please note that these are strings that are autoreleased. If you want to keep them, retain it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜