加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何将字符串中的特定字符与下一个字符一起替换

发布时间:2020-12-17 03:42:28 所属栏目:百科 来源:网络整理
导读:我有一串文字: 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?
我有一串文字:

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和一个块来做到这一点:

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

使用块可以在每个匹配项上运行任意代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读