-2

I've seen other questions on here on how to remove all whitespace and newline characters using the actual NSString methods, but those affect the beginning of the string, which I do not want.

So let's say for example my user types the following string into my UITextView: H E Y \n \n

There are two spaces after the letter Y followed by a new line character, two more spaces, and lastly another new line character in the above example.

What I would like is for everything after the letter Y to be removed from the UITextView's string.

I'd appreciate any pointers to help me solve this.

- (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)];
}
klcjr89
  • 5,862
  • 10
  • 58
  • 91

1 Answers1

-5

You can use:

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

I tested in Xcode with:

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

Result is:

textView.text = [H E Y]
Duyen LE
  • 22
  • 1