我在这里看到了其他有关如何使用实际的NSString方法删除所有空格和换行符的问题,但是这些问题会影响字符串的开头,而这是我所不希望的。
例如,假设我的用户在我的UITextView中键入以下字符串:HEY \ 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)];
}
您可以使用:
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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句