我的字符串是@"Hello, I am working as an ios developer"
现在我要删除单词"ios"
最终我要删除最后一个空格字符后的所有字符。
我怎样才能做到这一点?
答案 0 :(得分:9)
示例代码:
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"
答案 1 :(得分: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"
答案 2 :(得分:1)
您也可以使用REGEX实现此目的
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”关键字,并在文字后丢弃
希望它会有所帮助。