gpt4 book ai didi

ruby - 更改字符串的特定索引,必要时进行填充

转载 作者:数据小太阳 更新时间:2023-10-29 08:45:10 24 4
gpt4 key购买 nike

我有一个名为 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 length integer with [the return value] left justified and padded with padstr; otherwise, returns [an unmodified version of the receiver].

indicators = indicators.ljust(7)
indicators[6] = "R"

关于ruby - 更改字符串的特定索引,必要时进行填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30718309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com