【发布时间】:2015-01-21 07:16:10
【问题描述】:
我的字符串是@"Hello, I am working as an ios developer"
现在我想删除单词"ios"之后的所有字符
最终我想删除最后一个空格字符之后的所有字符。
我怎样才能做到这一点?
【问题讨论】:
标签: objective-c iphone nsstring
我的字符串是@"Hello, I am working as an ios developer"
现在我想删除单词"ios"之后的所有字符
最终我想删除最后一个空格字符之后的所有字符。
我怎样才能做到这一点?
【问题讨论】:
标签: objective-c iphone nsstring
示例代码:
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"
【讨论】:
您也可以使用 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”关键字并在单词之后丢弃
希望它会有所帮助。
【讨论】: