NSString - 删除最后一个空格之后的所有字符

3

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

现在我想删除单词"ios"后面的所有字符。

最终我想要删除最后一个空格字符后面的所有字符。

我该如何实现这个目标?

3个回答

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" 

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”关键字并且会忽略之后的单词。
希望能对您有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接