How to count '\\n' in an UITextView

2019-08-29 13:45发布

问题:

I got a headache trying to count returns (\n) in my UITextView. As you'll soon realise, I'm a bloody beginner and here is my theory of what I've come up with, but there are many gaps...

- (IBAction)countReturns:(id)sender {

int returns;

while ((textView = getchar()) != endOfString [if there is such a thing?])
{
   if (textView = getchar()) == '\n') {
   returns++;
   }
}

NSString *newText = [[NSString alloc] initWithFormat:@"Number of returns: %d", returns];
    numberReturns.text = newText;

    [newText release];
    }   

I checked other questions on here, but people are usually (in my eyes) lost in some details which I don't understand. Any help would be very much appreciated! Thanks for your patience.

回答1:

You can simply

UITextView *theview; //remove this line, and change future theview to your veiw
NSString *thestring; //for storing a string from your view
int returnint = 0;
thestring = [NSString stringWithFormat:@"%@",[theview text]];

for (int temp = 0; temp < [thestring length]; temp++){ //run through the string
if ([thestring characterAtIndex: temp] == '\n')
    returnint++;
}


回答2:

NSArray *newlines = [textView.text componentsSeparatedByString:@"\n"];
int returns = ([newlines count]-1)

Should work. Keep in mind this isn't such a great idea if you have a gia-normous string, but it's quick, dirty and easy to implement.



回答3:

there are a lot of ways to do that. Here is one:

NSString *str = @"FooBar\n\nBaz...\n\nABC\n";
NSString *tmpStr = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSInteger count = [str length] - [tmpStr length];
NSLog(@"Count: %d", count);