0

I found a lot of examples how to find string between 2 strings, but none of which shows how to handle multiple occurrences of that string. I have for example string like this

"Hi, I am <id>User</id>. I am 20 <id>years old</id>, and live in <id>some country</id>."

The idea behind is that I want to hyperlink each occurrence of that string within UITextField, and remove tags from the string. I also have 2 types of the tag, one should display hyperlink, the other should popup alert view with some text description of the word or phrase clicked.

EDIT:

Found a perfectly good working solution to extend this logic with changing content of the text with attributed string between tags provided in the text. Link here.

Aleksandar
  • 1,457
  • 13
  • 30

2 Answers2

1

@Aleksandar Try this.. it works for me..

NSString *serverOutput = @"Hi, I am <id>User</id>. I am 20 <id>years old</id>, and live in <id>some country</id>.";
    if([serverOutput containsString:@"</id>"])
    {
        NSArray *arrSeparate = [serverOutput componentsSeparatedByString:@"</id>"];
        NSString *output = @"";
        for(int i=0; i<arrSeparate.count; i++)
        {
            if([[arrSeparate objectAtIndex:i] containsString:@"<id>"])
            {
                NSArray *arrTest = [[arrSeparate objectAtIndex:i] componentsSeparatedByString:@"<id>"];
                if(output.length < 1)
                    output = [arrTest objectAtIndex:1];
                else
                    output = [NSString stringWithFormat:@"%@\n%@",output,[arrTest objectAtIndex:1]];
            }
        }
        serverOutput = output;
    }
    NSLog(@"%@", serverOutput);
Nirav Kotecha
  • 2,493
  • 1
  • 12
  • 26
  • 1
    Yes, this works for me as well. I can work from there to achieve what I need. Both you and @gurmandeep gave a working solution. – Aleksandar Nov 08 '17 at 09:46
1

Please look into this, and i hope this gets you all the range where the keyword exists

NSString *serverOutput = @"Hi, I am <id>User</id>. I am 20 <id>years old</id>, and live in <id>some country</id>";
NSUInteger count = 0, length = [serverOutput length];
NSRange startRange = NSMakeRange(0, length);
NSRange endRange = NSMakeRange(0, length);
while(startRange.location != NSNotFound)
{
    startRange = [serverOutput rangeOfString: @"<id>" options:0 range:startRange];
    if(startRange.location != NSNotFound)
    {
        endRange = [serverOutput rangeOfString: @"</id>" options:0 range:endRange];
        startRange = NSMakeRange(startRange.location + startRange.length, length - (startRange.location + startRange.length));
        endRange = NSMakeRange(endRange.location + endRange.length, length - (endRange.location + endRange.length));
        count++;
    }
}

startRange will be the range from where the tag starts and endRange is where starts

You can change the range, location, create attributed string and add hyperlink as the range of string is available to you.

gurmandeep
  • 1,227
  • 1
  • 14
  • 30