我在这里看到了关于如何使用实际的 NSString 方法删除所有空格和换行符的其他问题,但这些问题会影响字符串的开头,这是我不想要的。
例如,假设我的用户在我的 UITextView 中键入以下字符串:H E Y
在上面的示例中,字母 Y 后有两个空格,后跟一个新行字符,另外两个空格,最后是另一个换行符。
我想要的是将字母 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)];
}
您可以使用:
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]