拼音:仅反转字符串的前 100 个字符



我正在尝试对 Ruby 中的字符串进行一些字符串操作。目标是仅剥离、反转、挤压和大写前 100 个字符,而不会影响字符串的其余部分。

这是我们将使用的字符串。行号是字符串的一部分。在赋值中,此字符串称为"the_string"。

1.               this string has leading space and too    "MANY tabs and sPaCes betweenX"
2.   thE indiVidual Words in each Line.X
3.  eacH Line ends with a accidentally  aDDED   X.X
4.            in this lab you wilL WRITE code that "sAnITizES" this string by normalizingX
5.   ("nOrMaLiZiNg" means   capitalizing sentences   and setting otherX
6.  characterS to lower case)     and removes         the extra spaces between WOrds.X

这是我的工作:

puts the_string[0,100].strip.squeeze.reverse.upcase 

和输出:

I EHT .2
"XNEWTEB SECAPS DNA SBAT YNAM" OT DNA ECAPS GNIDAEL SAH GNIRTS SIHT .1

这是按照我想要的方式工作的,除了不是从字符串中删除剩余的字符(100 之后),而是希望它们保持原位且不变。此外,我不应该修改object_id,因此我无法创建一个新字符串来解决此问题。我寻求的输出是:

I EHT .2
"XNEEWTEB SECAPS DNA SBAT YNAM" OOT DNA ECAPS GNIDAEL SAH GNIRTS SIHT .1ndiVidual Words in each Line.X
3.  eacH Line ends with a accidentally  aDDED   X.X
4.            in this lab you wilL WRITE code that "sAnITizES" this string by normalizingX
5.   ("nOrMaLiZiNg" means   capitalizing sentences   and setting otherX
6.  characterS to lower case)     and removes         the extra spaces between WOrds.X

我确信有一种方法可以简化此操作,我只是还没有发现优雅的解决方案。任何帮助将不胜感激!

您可以通过提供 Range 来替换字符串中的子字符串:

[1] pry(main)> string = "1234567890"
=> "1234567890"
[2] pry(main)> string.object_id
=> 70248091185880
[3] pry(main)> string[0...5]="abcde"
=> "abcde"
[4] pry(main)> string
=> "abcde67890"
[5] pry(main)> string.object_id
=> 70248091185880

因此,您的代码将如下所示:

the_string[0...100] = the_string[0,100].strip.squeeze.reverse.upcase 

我已经通过以下方式回答了我的问题:

substring = the_string[0,100].strip.squeeze.reverse.upcase 
the_string[0,100] = substring
puts the_string

最新更新