【问题标题】:How do I add spaces to the end of my string? [duplicate]如何在字符串末尾添加空格? [复制]
【发布时间】:2017-06-22 01:00:23
【问题描述】:

我使用的是 Ruby 2.4。如何在字符串末尾添加任意数量的空格?我以为只是,但是

2.4.0 :003 > line = "abcdef"
 => "abcdef"
2.4.0 :004 > line = line.ljust(4, " ")
 => "abcdef"

注意我的字符串没有改变。我做错了什么?

【问题讨论】:

    标签: ruby string padding


    【解决方案1】:

    ljust() 的整数必须大于字符串的长度,否则不会追加任何内容。由于line 是六个字符,我相信你想要:

    line = "abcdef"
    line = line.ljust(10, " ")
    

    这将在字符串中已经存在的六个字符之后添加四个空格。

    您可能还可以按照以下方式做一些事情:

    line = line.ljust(line.length + 4, " ")
    

    【讨论】:

      【解决方案2】:

      您可以添加多个空格:

      line = "abcdef"
      line + ' '*5
       #=> "abcdef     "
      line
       #=> "abcdef"
      

      或者使用修改字符串的concat

      line.concat(' '*5) 
       #=> "abcdef     "
      line
       #=> "abcdef     "
      

      【讨论】:

        猜你喜欢
        • 2022-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-18
        • 2016-04-26
        • 1970-01-01
        • 2011-03-16
        • 2020-07-15
        相关资源
        最近更新 更多