Search code examples
iosobjective-ciphonensrangensmutableattributedstring

How to extract a substring from a dynamic string in objective c?


I have a string like @"Greetings from Capt. Ashim Mittra,​ Vice President – Flight Operations" from which I want to extract “Capt. Ashim Mittra”. i.e. I want to start from the word “from” and read to “,” (comma)


Solution

  • You can do something like,

       NSString *str = @"Greetings from Capt. Ashim Mittra,​ Vice President – Flight Operations";
    
    NSRange range1 = [str rangeOfString:@"from"];
    NSRange range2 = [str rangeOfString:@","];
    NSRange rangeToSubString = NSMakeRange(range1.location + range1.length, range2.location - range1.location - range1.length);
    
    NSString *resultStr = [str substringWithRange:rangeToSubString];
    
    NSLog(@"path1 : %@",resultStr);
    

    you can set attributed text to your label or else when you want to show your text with bold portion something like,

      UIFont *font = [UIFont boldSystemFontOfSize:17.0]; // whatever size, can use diiferent font with different method
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
    
    NSMutableAttributedString *resultStrWithBold = [[NSMutableAttributedString alloc]initWithString:str];
    
    [resultStrWithBold setAttributes:dict range:rangeToSubString];
    
     yourLabel.attributedText = resultStrWithBold;