How do i search a string for a newline character? Both of the below seem to be returning -1....!
theJ = line.IndexOf(Environment.NewLine);
OR
theJ = line.IndexOf('\n');
The string it's searching is "yo\n" the string i'm parsing contains this "printf("yo\n");" the string i see contained during the comparison is this: "\tprintf(\"yo\n\");"
How do you check if a char is a new line? Simply comparing to '\n' should solve your problem; depending on what you consider to be a newline character, you might also want to check for '\r' (carriage return).
Open any text file and click on the pilcrow (¶) button. Notepad++ will show all of the characters with newline characters in either the CR and LF format. If it is a Windows EOL encoded file, the newline characters of CR LF will appear (\r\n). If the file is UNIX or Mac EOL encoded, then it will only show LF (\n).
The newline character is a single (typically 8-bit) character. It's represented in program source (either in a character literal or in a string literal) by the two-character sequence \n . So '\n' is a character constant representing a single character, the newline character.
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
"yo\n" // output as "yo" + newline
"yo\n".IndexOf('\n') // returns 2
"yo\\n" // output as "yo\n"
"yo\\n".IndexOf('\n') // returns -1
Are you sure you're searching yo\n
and not yo\\n
?
Based on your update, I can see that I guessed correctly. If your string says:
printf("yo\n");
... then this does not contain a newline character. If it did, it would look like this:
printf("yo
");
What it actually has is an escaped newline character, or in other words, a backslash character followed by an 'n'. That's why the string you're seeing when you debug is "\tprintf(\"yo\\n\");"
. If you want to find this character combination, you can use:
line.IndexOf("\\n")
For example:
"\tprintf(\"yo\\n\");" // output as " printf("yo\n");"
"\tprintf(\"yo\\n\");".IndexOf("\\n") // returns 11
Looks like your line does not contain a newline.
If you are using File.ReadAllLines
or string.Split
on newline, then each line in the returned array will not contain the newline. If you are using StreamReader
or one of the classes inheriting from it, the ReadLine
method will return the string without the newline.
string lotsOfLines = @"one
two
three";
string[] lines = lotsOfLines.Split('\n');
foreach(string line in lines)
{
Console.WriteLine(line.IndexOf('\n'); // prints -1 three times
}
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