在以下代码中:
static void Main(string[] args)
{
string MultiLineString = @"This is a
random sentence";
int index=0;
string test = "";
Console.WriteLine(MultiLineString[9].ToString()); //it should print 'r' but it prints a white space
for (int i = 0; i < MultiLineString.Length; i++)
{
if (MultiLineString[i] == 'r')
index = i;
}
Console.WriteLine(index); // 11 is the index of 'r' in "random"
foreach (char ch in MultiLineString)
if (ch == ' ')
test += "_";
else
test += ch;
Console.WriteLine(test);
// the output is:
// This_is_a
//random_sentece
}我很难理解9-10指数中正在发生的事情。起初,我以为这是我跳过一行时创建的一个空格,但后来它并没有包含在测试字符串中。
提前谢谢。
发布于 2013-01-27 02:54:46
MultiLineString[0] -> 'T'
MultiLineString[1] -> 'h'
MultiLineString[2] -> 'i'
MultiLineString[3] -> 's'
MultiLineString[4] -> ' '
MultiLineString[5] -> 'i'
MultiLineString[6] -> 's'
MultiLineString[7] -> ' '
MultiLineString[8] -> 'a'
MultiLineString[9] -> '\r'
MultiLineString[10] -> '\n'
MultiLineString[11] -> 'r'根据您的环境,换行符可以是"\r\n"、"\r"或"\n"。对于大多数Windows环境,换行符通常表示为"\r\n" (两个字符)。
通过执行以下操作,可以查看字符串中字符的ASCII值(而不仅仅是它们的可视化表示):
for(int i = 0; i < MultiLineString.Length; i++)
{
Console.WriteLine("{0} - {1}", i, (int)MultLineString[i]);
}\r将是13,\n将是10。
发布于 2013-01-27 02:53:58
当字符串声明为多行文字时,您显式地将新行包含到字符串("\n\r")中。换行符相应地位于位置9和10。
在SO:Multiline String Literal in C#上,C# language specification - string literals中也包含了“逐字字符串文字”。
与'\n' (10)和'\r' (13)不同,当您搜索由代码为32的字符组成的' '时,您只能找到实际的空格,而不是换行符“空白”字符。
注意,还有许多其他的“类空格”字符,所以如果您需要对它们执行一些特殊的处理,请查看Char.IsWhiteSpace等Char structure的方法
发布于 2013-01-27 03:00:29
正如其他人所说的,您没有考虑换行符转义序列\n,因此,您的索引减少了1。
以下面的代码为例:
using System;
public class Test
{
public static void Main()
{
string test = @"T
e
s
t";
for (int i =0 ; i < test.Length; i++)
{
Console.WriteLine("{0} == \\n? {1}", test[i], test[i] == '\n');
}
}
}输出为:
T == \n?假== \n?真的
E == \n?假== \n?真的
S == \n?错误
== \n?真的
T == \n?错误
如您所见,每隔一个字符就是一个换行符。
https://stackoverflow.com/questions/14540311
复制相似问题