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

时间:2021-01-13 20:08:44

I have a string of text:

我有一串文字:

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

I want to return the following:

我想返回以下内容:

"Hello World hoW is iT goinG

The % sign is a key that tells me the next character should be capitalized. The closest I have gotten so far is:

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

@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 returns:

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

It looks like I need to iterate through the string to make it work as it is only replacing the lowercase 't' but I can't get it to work.

看起来我需要遍历字符串以使其工作,因为它只是替换小写的't'但我无法让它工作。

2 个解决方案

#1


7  

You can do this with gsub and a block:

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

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

Using a block allows you to run arbitrary code on each match.

使用块可以在每次匹配时运行任意代码。

#2


1  

Inferior to @tadman, but you could write:

不如@tadman,但你可以写:

string.gsub(/%./, &:upcase).delete('%')
  #=> "Hello World hoW is iT goinG

#1


7  

You can do this with gsub and a block:

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

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

Using a block allows you to run arbitrary code on each match.

使用块可以在每次匹配时运行任意代码。

#2


1  

Inferior to @tadman, but you could write:

不如@tadman,但你可以写:

string.gsub(/%./, &:upcase).delete('%')
  #=> "Hello World hoW is iT goinG