我的字符串是@"Hello, I am working as an ios developer"
的NSString - 刪除最後一個空白後的所有字符
現在我想字"ios"
最後我想最後一個空格字符後刪除所有字符後,刪除所有字符。
我該如何做到這一點?
我的字符串是@"Hello, I am working as an ios developer"
的NSString - 刪除最後一個空白後的所有字符
現在我想字"ios"
最後我想最後一個空格字符後刪除所有字符後,刪除所有字符。
我該如何做到這一點?
示例代碼:
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"
我同意@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"
也可以達到這個使用正則表達式
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」關鍵字,並會丟棄後話
希望這將有助於。