NSString - 删除最后一个白色后的所有字符 space

NSString - remove all characters after last white space

我的字符串是@"Hello, I am working as an ios developer"

现在我想删除单词 "ios"

之后的所有字符

最终我想删除最后一个白色 space 字符之后的所有字符。

我怎样才能做到这一点?

示例代码:

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" 关键字并丢弃后面的词

希望对您有所帮助。