[英]Newline character not being added to string
This is my test code 这是我的测试代码
public string myMethod(int[,] anArray)
{
string aString = "";
for (int i = 0; i < anArray.GetLength(0); i++)
{
for (int j = 0; j < anArray.GetLength(1); j++)
{
if (j == anArray.Length - 1)
{
aString += " " + anArray[i, j] + "\r\n";
continue;
}
aString += anArray[i, j] + "|";
}
}
return aString;
}
When I call the method, I'm expecting a string that has newline characters in it. 当我调用该方法时,我期望一个包含换行符的字符串。
My desired result 我想要的结果
0|0|0
0|0|0
0|0|0
However I get this 但是我明白了
0|0|0|0|0|0|0|0|0|
Thanks. 谢谢。
EDIT: Silly mistake on the if condition, nothing more. 编辑:如果条件愚蠢的错误,仅此而已。
2nd EDIT: I had the wrong if condition statement in the latter portion of my code, leading to an incorrect string. 第2次编辑:我在代码的后半部分使用了错误的if条件语句,从而导致了错误的字符串。
String is immutable that is inefficient. 字符串是不可变的,效率很低。
StringBuild sb = new StringBuilder();
for ()
{
sb.AppendLine(" " + anArray[i, j]);
}
As per the comment 根据评论
anArray.GetLength(1)
anArray.Length
Not the same 不一样
if (j == anArray.Length - 1)
replaced by if (j == anArray.GetLength(1) - 1)
if (j == anArray.Length - 1)
替换为if (j == anArray.GetLength(1) - 1)
public string myMethod(int[,] anArray)
{
string aString = "";
for (int i = 0; i < anArray.GetLength(0); i++)
{
for (int j = 0; j < anArray.GetLength(1); j++)
{
if (j == anArray.GetLength(1) - 1)
{
aString += anArray[i, j] + "\r\n";
continue;
}
aString += anArray[i, j] + "|";
}
}
return aString;
}
Code should look like this: 代码应如下所示:
if (j == anArray.GetUpperBound(1))
{
aString += anArray[i, j] + "\r\n";
continue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.