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.
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' .
Important Note: I start the loop with index i = 1 because the first character acts like a command and is being treated specially.
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:
string line;
getline(cin,line);
For example, in Linux a new line is denoted by “\n”, also called a Line Feed. In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.
In Python, the new line character “\n” is used to create a new line.
"\n" is a character. char[] to represent a string needs "0" to mark the end of the string. In order to do that, char array requires one more element to store "0" but it is not counted as a string size.
"\n" is not a string containing a \
followed by an n
. The escape sequence \n
denotes a single character, which you can look for with
for (size_t i = 0; i < line.length(); i++)
if (line[i] == '\n')
// whatever
or with good old std::string::find
.
Instead of ( line[i]== ' \ ') && ( line[i+1] == 'n' )
, try
if ( line[i]== '\n')
and
i = i+1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With