Trim spaces from end of a NSString

前端 未结 14 1194
既然无缘
既然无缘 2020-11-27 09:26

I need to remove spaces from the end of a string. How can I do that? Example: if string is \"Hello \" it must become \"Hello\"

14条回答
  •  情话喂你
    2020-11-27 09:41

    I came up with this function, which basically behaves similarly to one in the answer by Alex:

    -(NSString*)trimLastSpace:(NSString*)str{
        int i = str.length - 1;
        for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
        return [str substringToIndex:i + 1];
    }
    

    whitespaceCharacterSet besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.

提交回复
热议问题