在obj-c中搜索String中的一行

时间:2011-07-22 12:22:02

标签: objective-c cocoa

我有一个由多行组成的String。例如:

line1 A B C

line2 X Y Z

line3 D E F

如何在该字符串中搜索Y并获得整行?所以我想把输出作为line2 X Y Z

3 个答案:

答案 0 :(得分:3)

一种方法是首先将字符串分成行:

NSArray *lines = [myString componentsSeparatedByString:@"\n"];

然后搜索一行:

for (NSString *line in lines) {
    NSRange *range = [line rangeOfString:@"Y"];
    if (range.length > 0) {
        // do something
    }
}

答案 1 :(得分:0)

Caleb答案的替代方案,如果您使用的是iOS 4.0或更高版本,则可以使用enumerateLinesUsingBlock

__block NSString * theLine;
[lines enumerateLinesUsingBlock:^(NSString * line, BOOL * stop){
    NSRange range = [line rangeOfString:@"Y"];
    if ( range.location != NSNotFound ) {
        theLine = [line retain];
        *stop = YES;
    }
}];

/* Use `theLine` for something */
[theLine release]; // Relinquish ownership

答案 2 :(得分:0)

你可以做这样的事情

- (NSString *)LineTextFinder:(NSString*)inData Serach:(char)inSearch LineDelimiter:(char)inChar
{
    int lineStart = 0;
    int lineEnd =0;

    int i = 0;
    BOOL found = NO;

    while (1)
    {
        if(i > [inData length])
        {
            lineStart = lineEnd;
            lineEnd = i;

            break;
        }
        if (inChar == [inData characterAtIndex:i])
        {
            lineStart = lineEnd;
            lineEnd = i;


            //we can brack only when we travell end of found line
            if (found)
            {
                break;
            }
        }

        if(inSearch == [inData characterAtIndex:i])
        {
            found = YES;
        }
        i++;
    }


    NSString *returnStr = nil;
    if ((found))
    {
        NSRange splitRange = {lineStart,(lineEnd-lineStart)};
        returnStr = [inData substringWithRange:splitRange];
    }

    return returnStr;
}