【问题标题】:NSString - remove all characters after last white spaceNSString - 删除最后一个空格后的所有字符
【发布时间】:2015-01-21 07:16:10
【问题描述】:

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

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

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

我怎样才能做到这一点?

【问题讨论】:

    标签: objective-c iphone nsstring


    【解决方案1】:

    示例代码:

    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" 
    

    【讨论】:

      【解决方案2】:

      我同意@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"
      

      【讨论】:

        【解决方案3】:

        您也可以使用 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”关键字并在单词之后丢弃

        希望它会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-23
          • 1970-01-01
          • 1970-01-01
          • 2023-01-30
          • 1970-01-01
          • 2017-03-01
          相关资源
          最近更新 更多