2016-08-01 102 views
0

我有一個字符串,如@"Greetings from Capt. Ashim Mittra,​ Vice President – Flight Operations",我想從中提取「Capt。阿希姆米特拉「。即我想從「從」字開始,讀「」(逗號)如何從目標c中的動態字符串中提取子字符串?

+1

你已經嘗試過這樣做顯示的代碼。 –

+0

'substringWithRange'和'rangeOfString:'可以使用。對於「大膽」的用戶界面,這取決於。你可以使用'NSAttributedString',如果有一些粗體文本,或者只是使用'UILabel''''UITextView'的'font'屬性... – Larme

+0

如何使用正則表達式? – Eiko

回答

0

你可以做這樣的事情,

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); 

可以歸因文字設爲您的標籤,否則當你想展現大膽一部分喜歡你的文字,

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; 
1

使用此代碼:

NSString * yourStr = @"Greetings from Capt. Ashim Mittra,​ Vice President – Flight Operations"; 
NSRange range1 = [yourStr rangeOfString:@"from"]; 
NSRange range2 = [yourStr rangeOfString:@","]; 
NSRange rangeSubString = NSMakeRange(range1.location + range1.length, range2.location - range1.location - range1.length); 
NSString *finalString = [yourStr substringWithRange: rangeSubString]; 

爲了讓大膽地使用這一點;

NSMutableAttributedString * yourAttributedString = [[NSMutableAttributedString alloc] initWithString: finalString]; 
[yourAttributedString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:NSMakeRange(0,finalString)]; 
[yourLbl setAttributedText: yourAttributedString]; 
+0

否錯誤檢查! – Droppy

2

您可以使用正則表達式來查找名稱 - 這裏是一個示例:

​​

這可能需要改進很多,但您需要檢查所有輸入數據以進行正確調整。它會在輸入字符串中找到幾個名稱。

-1

您可以使用下面的代碼:

- (void)viewDidLoad { 
[super viewDidLoad]; 
NSString *str = @"Greetings from Capt. Ashim Mittra ,​ Vice President – Flight Operations"; 
NSString *fromString = @"from"; 
NSString *toString = @","; 

NSArray *seperatorArr = [[NSArray alloc] initWithObjects:fromString, toString, nil]; 
NSString *reqStr = [self extractSubstringFrom:str seperatedBy:seperatorArr]; 
} 

- (NSString *)extractSubstringFrom:(NSString *)string seperatedBy:(NSArray *)seperatorArray { 

NSString *resultingString = string; 

for (int i = 0; i < seperatorArray.count; i++) { 
    NSArray *newStrArr = [resultingString componentsSeparatedByString:[seperatorArray objectAtIndex:i]]; 
    if (i == seperatorArray.count - 1) { 
     resultingString = [newStrArr firstObject]; 
    } 
    else 
     resultingString = [newStrArr lastObject]; 
} 
NSLog(@"Resulting String = %@",resultingString); 
return resultingString; 

}

相關問題