【问题标题】:How to trim all whitespace and new line characters at end of UITextView's string [duplicate]如何修剪UITextView字符串末尾的所有空格和换行符[重复]
【发布时间】:2014-03-19 03:19:34
【问题描述】:

我在这里看到了关于如何使用实际的 NSString 方法删除所有空格和换行符的其他问题,但是这些会影响字符串的开头,这是我不想要的。

假设我的用户在我的 UITextView 中键入以下字符串:H E Y \n \n

在上面的例子中,字母 Y 后面有两个空格,后跟一个换行符,另外两个空格,最后一个换行符。

我想要的是从 UITextView 的字符串中删除字母 Y 之后的所有内容。

如果有任何建议可以帮助我解决这个问题,我将不胜感激。

- (void)textViewDidEndEditing:(UITextView *)textView
{
     textView.text = [self removeCrapFrom:textView.text];
}

- (NSString *)removeCrapFrom:(NSString *)string
{
    NSUInteger location = 0;
    unichar charBuffer[[string length]];
    [string getCharacters:charBuffer];
    int i = 0;
    for (i = [string length]; i >0; i--)
    {
        if (![[NSCharacterSet whitespaceAndNewlineCharacterSet] characterIsMember:charBuffer[i - 1]])
        {
            break;
        }
    }
    return  [string substringWithRange:NSMakeRange(location, i  - location)];
}

【问题讨论】:

  • 其他答案有什么问题?
  • 就像我说的,它们会影响开头和结尾,这是我不想要的
  • 那你为什么不发布一个开头有空格/字符的字符串的例子呢?
  • 我确实做到了。 H E Y \n \n 就是一个例子。
  • 它没有帮助吗?我认为downvoters 会乞求与你不同。

标签: ios objective-c ios7 nsstring uitextview


【解决方案1】:

你可以使用:

NSString *newString = [aString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

我在 Xcode 中测试过:

UITextView *textView = [[UITextView alloc] init];
textView.text = @"H E Y \n \n";
textView.text = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"textView.text = [%@]",textView.text);

结果是:

textView.text = [H E Y]

【讨论】:

  • 请阅读cmets中的问题和讨论。
猜你喜欢
  • 1970-01-01
  • 2013-09-11
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
相关资源
最近更新 更多