C++ 在字符串对象中搜索换行符 '\n'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8636125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:54:25  来源:igfitidea点击:

Searching for newline '\n' character within a string object

c++

提问by Vaios Argiropoulos

I have a string object of the general form string line = "yadayada\nyadaya". I loop through the string as below trying to "catch" the newline character.

我有一个一般形式的字符串对象string line = "yadayada\nyadaya"。我循环遍历字符串,如下所示,试图“捕获”换行符。

        for (int i = 1; i < line.length(); i++)
        {
             if ( ( line[i]== ' \ ') && ( line[i+1] == 'n' ) ) 
             {
                  buffer.insertChar('\n');
                  i = i+2;
             }
             else
             {

                  buffer.insertChar(line[i]);
             }

        }

As you can see i loop through the string characters and i am inserting the characters one by one in another object called buffer (irrelevant to the question).

如您所见,我遍历字符串字符,并将字符一个接一个地插入到另一个名为缓冲区的对象中(与问题无关)。

In the first if if ( ( line[i]== ' \ ') && ( line[i+1] == 'n' ) )i am trying to "catch" the newline character and inside that if body i am incrementing the index i by two so that it will skip the characters '\' and 'n' in the next loop. The problem is that this loop never catches a newline character but always inserts in the buffer the two individual characters '\' and 'n' .

在第一个中,如果if ( ( line[i]== ' \ ') && ( line[i+1] == 'n' ) )我试图“捕获”换行符,而在其中的 if 正文中,我将索引 i 增加 2,以便在下一个循环中跳过字符 '\' 和 'n'。问题是这个循环永远不会捕获换行符,而是总是在缓冲区中插入两个单独的字符 '\' 和 'n' 。

Important Note: I start the loop with index i = 1 because the first character acts like a command and is being treated specially.

重要说明:我以索引 i = 1 开始循环,因为第一个字符的作用类似于命令并且被特殊对待。

Update: I modified the above code but still no luck with what i am trying to accomplish

更新:我修改了上面的代码,但仍然没有完成我想要完成的工作

                for (int i = 1; i < line.length(); i++)
                {
                    if ( (line[i]== '\n') )   
                    {

                        buffer.insertChar('\n');
                        i = i+1;
                    }
                    else
                    {

                        buffer.insertChar(line[i]);
                    }

                }

Update # 2 : If that helps the string is being originated from input of the user like below:

更新#2:如果这有助于字符串来自用户的输入,如下所示:

string line;
getline(cin,line);

回答by Fred Foo

"\n" is not a string containing a \followed by an n. The escape sequence \ndenotes a single character, which you can look for with

"\n" 不是包含\后跟一个的字符串n。转义序列\n表示单个字符,您可以使用它查找

for (size_t i = 0; i < line.length(); i++)
     if (line[i] == '\n')
         // whatever

or with good old std::string::find.

或与好旧std::string::find

回答by c0da

Instead of ( line[i]== ' \ ') && ( line[i+1] == 'n' ), try

而不是( line[i]== ' \ ') && ( line[i+1] == 'n' ),尝试

if ( line[i]== '\n')

if ( line[i]== '\n')

and

i = i+1;

i = i+1;

回答by apocalypse

'\n' is one char, not two.

'\n' 是一个字符,而不是两个。

try:

尝试:

if (line[i] == '\n') ...

回答by Lorenzo Pistone

I'm not sure if you're searching for the sequence of character '\' plus 'n' or the newline (whose representation in a C source file is indeed \n, but that corresponds to a single byte!), but in both cases, this should be ok:

我不确定您是在搜索字符 '\' 加 'n' 的序列还是换行符(其在 C 源文件中的表示确实是 \n,但它对应于单个字节!),但是在这两种情况,这应该没问题:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string pattern("\n");      //or, "\n", so \n is actually '\' plus 'n'
    string input="yadayada\nyayda\nyadayada";
    size_t index;
    while((index=input.find_first_of(pattern))!=string::npos)
        input=input.substr(0, index)+input.substr(index+pattern.size());
    cout<<input;
}

This example prints yadayadayayda\nyadayada, which is probably what you want.

此示例打印yadayadayayda\nyadayada,这可能是您想要的。

回答by Lorenzo Pistone

In string line = "yadayada\nyadaya", there is one character between "yadayada"and "yadaya". Did you mean "yadayada\\nyadaya", which you are trying to convert to "yadayada\nyadaya"?

在 中string line = "yadayada\nyadaya""yadayada"和之间有一个字符"yadaya"。您的意思是"yadayada\\nyadaya",您要转换为"yadayada\nyadaya"哪个?

' \ 'should be '\\'. I'm guessing you tried '\', got a compiler error, and figured you'd try adding some characters until it compiled? That's a bad idea. ' \ ', if it's accepted by the compiler at all, will never match.

' \ '应该是'\\'。我猜你试过'\',遇到编译器错误,并认为你会尝试添加一些字符直到它编译?这是个坏主意。' \ ',如果它被编译器完全接受,则永远不会匹配。

There's also one more problem: i = i+2;increases i by 2, but you then go to the i++, so you increase i by a total of 3.

还有一个问题:i = i+2;将 i 增加 2,但您随后转到i++,因此您将 i 总共增加 3。

回答by Alpha01

There are a couple of problems with the code:

代码有几个问题:

  1. if you assume that '\' and 'n' are two different characters, if the '\' is at the end of the code, you would run out of the array! you need to put to the if condition if the i<n-1

  2. '\' and 'n' are usually one character, so you do test line[i] == '\n'.

  3. Your i=i+2 is wrong as you always increment by 1 by the for loop itself, so just i++ in the condition is fine

  1. 如果你假设 '\' 和 'n' 是两个不同的字符,如果 '\' 在代码的末尾,你就会用完数组!如果i<n-1

  2. '\' 和 'n' 通常是一个字符,所以你做 test line[i] == '\n'

  3. 你的 i=i+2 是错误的,因为你总是通过 for 循环本身增加 1,所以只有 i++ 在条件中就可以了

More fundamentally, what are you actually trying to achieve? Are you just trying to remove \n from the string? Why not to use standard string replace functions!!!!

更根本的是,你真正想要达到什么目标?你只是想从字符串中删除 \n 吗?为什么不使用标准的字符串替换函数!!!!