1

I have a String which consists of multiple lines. ex:

line1 A B C

line2 X Y Z

line3 D E F

How can I search for Y in that string and get the whole line? So I would like to get the output as line2 X Y Z

ed1t
  • 8,719
  • 17
  • 67
  • 110

3 Answers3

3

One way is to break the string up into lines first:

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

And then search through the lines:

for (NSString *line in lines) {
    NSRange *range = [line rangeOfString:@"Y"];
    if (range.length > 0) {
        // do something
    }
}
Caleb
  • 124,013
  • 19
  • 183
  • 272
0

An alternative to Caleb's answer and if you are using iOS 4.0 or later, you can use 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
Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
0

You can done some thing like this

- (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;
}
Girish Kolari
  • 2,515
  • 2
  • 24
  • 34