简体   繁体   中英

How could I substring an NSString to the third occurrence of a character?

I want to count the ',' characters and substring when it has been repeated 3 times.

Input:

9,1,2,3,9

Output:

9,1,2

I am pretty sure something that specific would not have a build in method. Off the top of my head:

for(unsigned int i = 0; i < [string length]; ++i)
{
    if([string characterAtIndex:i] == ',')
    {
         ++commaCount;
         if(commaCount == 3)
         {
              return [string substringWithRange: NSMakeRange(0, i)];
         }
     }
}

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

The apple reference documents are usually a good place to start.

[yourString substringFromIndex:[yourString rangeOfString:@","].location]

这样的事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM