2015-01-21 160 views

回答

8

示例代碼:

NSString* str= @"Hello, I am working as an ios developer"; 

// Search from back to get the last space character 
NSRange range= [str rangeOfString: @" " options: NSBackwardsSearch]; 

// Take the first substring: from 0 to the space character 
NSString* finalStr = [str substringToIndex: range.location]; // @"Hello, I am working as an ios" 
4

我同意@Bhavin,但我認爲,更多更好地利用[NSCharacterSet whitespaceCharacterSet]確定的空白字符。

NSString* str= @"Hello, I am working as an ios developer"; 

    // Search from back to get the last space character 
    NSRange range= [str rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet] options:NSBackwardsSearch]; 

    // Take the first substring: from 0 to the space character 
    NSString* finalStr = [str substringToIndex: range.location]; // @"Hello, I am working as an ios" 
1

也可以達到這個使用正則表達式

NSString* str= @"Hello, I am working as an ios developer"; 
NSString *regEx = [NSString stringWithFormat:@"ios"];///Make a regex 
NSRange range = [str rangeOfString:regEx options:NSRegularExpressionSearch]; 
if (range.location != NSNotFound) 
{ 

    NSString *subStr=[str substringToIndex:(range.location+range.length)]; 
} 

這將搜索第一「IOS」關鍵字,並會丟棄後話

希望這將有助於。

相關問題