2014-02-19 88 views
-3

我已经看到了这里如何使用实际的NSString的方法来移除所有的空格和换行符其他问题的结束,但这些影响字符串的开头这我不想。如何修剪所有空格和换行字符在UITextView中的字符串

因此,让我们说,例如我的用户键入以下命令串到我的UITextView:HEY \ n \ n

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

我想什么是一切书后从UITextView中的字符串,删除年。

我会很感激任何指针,以帮助我解决这个问题。

- (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)]; 
} 
+0

什么是错的其他的答案? – nhgrif

+0

就像我说的,他们影响的开始和结束,我不希望 – klcjr89

+0

那你为什么不公布与开头空格/字符的字符串的例子吗? – nhgrif

回答

-6

您可以使用:

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] 
+0

请阅读评论中的问题和讨论。 – nhgrif