开发者

check if a character is carriage return

开发者 https://www.devze.com 2023-04-06 12:13 出处:网络
i would like to remove the last line from my string.. the nsstring object here is _text. My thoughts are to scan characters from the end and if i found a carriage return symbol i substring to that ind

i would like to remove the last line from my string.. the nsstring object here is _text. My thoughts are to scan characters from the end and if i found a carriage return symbol i substring to that index, and finnish. But i don't want to remove every carriage return, just the last one.

So i would like to do something like this:

for (int i = [_text length] ; i>0; i--) {
    char character = [_text characterAtIndex:i];
    if (character == @"\n") {
       _text = [_text sub开发者_C百科stringToIndex:i];
     return;
    }
}

Any help would be very appreciated! Thanks.


Your approach is correct, but you're checking if a char is equal to a literal string pointer! Try this instead:

 if (character == '\n')
       ...

By the way, this is a newline. A carriage return is represented by '\r'. Also, as a word of caution, review your memory management. If _text is an ivar, you may want to use a setter instead. Otherwise, you're assigning an autoreleased object to it that probably won't exist anymore in a latter path, causing other problems.


You might try:

NSString *newString = [originalString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];

It will remove all leading and trailing carriage returns '\r' and new lines '\n'.


You should handle the last char being whitespace or CR. You also had a bug where you needed length - 1 in the for loop.

Here's some working code:

    NSString *_text = [NSString stringWithString:@"line number 1\nline number 2\nlinenumber 3\n  "];

    // make sure you handle ending whitespace and ending carriage return
    _text = [_text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSUInteger i;
    unichar cr = '\n';
    for (i = [_text length] - 1; i>0; i--) 
    {
        if ([_text characterAtIndex:i] == cr) 
        {
            break;
        }
    }

    if (index > 0)
    {
        _text = [_text substringToIndex:i];
    }

    NSLog(@"%@", _text);

This outputs: 2011-09-22 08:00:10.473 Craplet[667:707] line number 1 line number 2


Try this -

if([_text characterAtIndex:[albumName length]-1] == '\n') //compare last char
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号