给出以下代码:
String indentation = "";
List < int > indents = [ 0, 1, 2, 4, 6, 8 ];
int length = 0;
for ( int i = 0; ( i <= 8 ); i++ )
{
if ( indents.contains ( i ) )
{
indentation = " ".padLeft(i);
length = indentation.length;
print ( "indent: $i length: $length indentation: '$indentation'");
}
}
我得到以下结果:
indent: 0 length: 1 indentation: ' '
indent: 1 length: 1 indentation: ' '
indent: 2 length: 2 indentation: ' '
indent: 4 length: 4 indentation: ' '
indent: 6 length: 6 indentation: ' '
indent: 8 length: 8 indentation: ' '
我认为“” .leftPad(0)的结果不应与“” .leftPad(1)的结果相同。我可以使用零的缩进测试来解决。但是,我认为这是一个编译器错误。
答案 0 :(得分:3)
这是您的问题:
indentation = " ".padLeft(i);
padLeft
确保字符串开头至少有一定数量的空格,并且仅在必要时才添加更多空格。因为您是在单个空格(" "
)的字符串上调用它,所以padLeft(1)
会在字符串的开头看到确实存在一个空格,并会认为其工作已完成。因此,padLeft(0)
和padLeft(1)
将完成相同的工作量-根本没有。
将" "
更改为""
会产生预期的结果:
indent: 0 length: 0 indentation: ''
indent: 1 length: 1 indentation: ' '
indent: 2 length: 2 indentation: ' '
indent: 4 length: 4 indentation: ' '
indent: 6 length: 6 indentation: ' '
indent: 8 length: 8 indentation: ' '