简体   繁体   English

检查字符是否是回车符

[英]check if a character is carriage return

i would like to remove the last line from my string.. the nsstring object here is _text. 我想从我的字符串中删除最后一行。.nsstring对象是_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 substringToIndex: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! 您的方法是正确的,但是您正在检查char是否等于文字字符串指针! Try this instead: 试试这个:

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

By the way, this is a newline. 顺便说一句,这是换行符。 A carriage return is represented by '\\r' . 回车由'\\r' Also, as a word of caution, review your memory management. 另外,请谨慎查看内存管理。 If _text is an ivar, you may want to use a setter instead. 如果_text是ivar,则可能要使用setter。 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'. 它将删除所有前导和尾随的回车符'\\ r'和新行'\\ n'。

You should handle the last char being whitespace or CR. 您应该处理最后一个字符,即空格或CR。 You also had a bug where you needed length - 1 in the for loop. 您还遇到了一个需要长度的错误-for循环中为1。

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 输出:2011-09-22 08:00:10.473 Craplet [667:707]行号1行号2

尝试这个 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM