为了“填充”我正在打印的数字,以便它始终是固定数量的字符,我正在根据有多少整数和给定数字制作填充字符串:
pad := ' '.
(freqVal < 10) ifTrue: [ pad := ' ' ].
((freqVal < 100) & (freqVal > 9)) ifTrue: [ pad := ' ' ].
((freqVal < 1000) & (freqVal > 99)) ifTrue: [ pad := ' ' ].
stdout<<pad<<freqVal<<<<nl
但是,打印结果总是使变量pad
成为一个字母而不是像我正在赋值的空格。如果我在最后一行之前添加pad displayNl
,它会出于某种原因打印出一个字母,而不仅仅是空格。
有什么想法可能会发生吗?
我特别不知道Gnu-Smalltalk。当然,有一些方便的String方法或格式化程序可以为此目的重用。我的建议是首先将数字转换为String,然后使用空白填充格式化它。这样你就可以避免你遇到的类型转换问题
新的String方法(最好是ST分配中的现有方法):
withLeading: aCharacter size: anInteger
(anInteger < self size) ifTrue: [^self copyFrom: 1 to: anInteger].
^((self species new: anInteger - self size) atAllPut: aCharacter ), self
用法示例
9 asString withLeading: ($ ) size: 10 "result ' 9'"
10 asString withLeading: ($ ) size: 10 "result ' 10'"
999 asString withLeading: ($ ) size: 10 "result ' 999'"