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

戏子无情 提交于 2019-12-20 01:43:57

问题


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

回答1:


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.




回答2:


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

Something like that.



来源:https://stackoverflow.com/questions/7504115/how-could-i-substring-an-nsstring-to-the-third-occurrence-of-a-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!