gpt4 book ai didi

ruby - 如何替换字符串中的特定字符以及紧邻的下一个字符

转载 作者:数据小太阳 更新时间:2023-10-29 07:25:31 26 4
gpt4 key购买 nike

我有一串文字:

string = "%hello %world ho%w is i%t goin%g"

我要返回以下内容:

"Hello World hoW is iT goinG

% 符号是告诉我下一个字符应该大写的键。到目前为止我得到的最接近的是:

@thing = "%this is a %test this is %only a %test"

if @thing.include?('%')
indicator_position = @thing.index("%")
lowercase_letter_position = indicator_position + 1
lowercase_letter = @thing[lowercase_letter_position]

@thing.gsub!("%#{lowercase_letter}","#{lowercase_letter.upcase}")
end

返回:

"This is a Test this is %only a Test"

看起来我需要遍历字符串才能使其正常工作,因为它只是替换了小写字母“t”,但我无法使其正常工作。

最佳答案

你可以用 gsub 和一个 block 来做到这一点:

string.gsub(/%(.)/) do |m|
m[1].upcase
end

使用 block 允许您在每次匹配时运行任意代码。

关于ruby - 如何替换字符串中的特定字符以及紧邻的下一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37420332/

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