我有一个名为 indicators
的字符串,该应用程序的原始开发人员用它来存储单个字符来指示模型的某些组件。我需要更改字符串中的第 7 个字符,我尝试使用以下代码来完成此操作:
indicators[6] = "R"
我很快发现问题是字符串并不总是 7 个字符长。例如,我有一组带有 U 2
的值,我需要将其转换为 U 2 R
(在 2 之后添加一个额外的空格)。有没有一种简单的方法可以用 Ruby 强制进行字符计数?
最佳答案
使用String.ljust(integer, padstr=' ')
If
integer
is greater than the length of [the receiver], returns a new String of lengthinteger
with [the return value] left justified and padded withpadstr
; otherwise, returns [an unmodified version of the receiver].
indicators = indicators.ljust(7)
indicators[6] = "R"
关于ruby - 更改字符串的特定索引,必要时进行填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30718309/