问题描述
如何在字符串中搜索换行符?下面的两个似乎都返回-1 ....!
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');
正在搜索的字符串为 yo\n
我正在解析的字符串包含此 printf( yo\n);
我在比较中看到的字符串是这样的: \tprintf(\ yo\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\");"
推荐答案
"yo\n" // output as "yo" + newline
"yo\n".IndexOf('\n') // returns 2
"yo\\n" // output as "yo\n"
"yo\\n".IndexOf('\n') // returns -1
确定要搜索 yo\n
而不是 yo ?
根据您的更新,我可以看到我猜对了。如果您的字符串说:
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
");
实际上它是一个转义的换行符,或者换句话说,一个反斜杠字符后跟一个'n'。因此,您在调试时看到的字符串是 \tprintf(\ yo\\n\);
。如果要查找此字符组合,则可以使用:
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")
例如:
"\tprintf(\"yo\\n\");" // output as " printf("yo\n");"
"\tprintf(\"yo\\n\");".IndexOf("\\n") // returns 11
这篇关于搜索换行符C#.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!