Reputation: 187
I already know how to replace a character at a given index, but I am looking to replace every character except the one at the index given.
For example, I have the string "011010010"
and want to replace every character with "0"
, except the first occurrence of "1"
. I use String#index("1")
to find the index of the first "1"
, but from there, how would I go about changing the string to "010000000"
?
Upvotes: 2
Views: 539
Reputation: 121000
test = "011010010"
test.sub(/(0*1)(.*)/) { $1 << '0'*$2.length }
#⇒ "010000000"
test =~ /1/ && $` << '1' << '0'*$'.length || test # C'`mon parser
#⇒ "010000000"
Upvotes: 1
Reputation: 110725
str = "011010010"
str[/0*1/].ljust(str.size,'0')
#=> "010000000"
Upvotes: 2
Reputation: 168199
flag = false
"011010010".gsub(/./){|s| (flag ? "0" : s).tap{flag = true if s == "1"}}
Upvotes: 1
Reputation: 10034
Maybe something like that, changing only characters after the first match:
str = "010010110"
first_occurence = str.index('1')
results = "#{str[0..first_occurence]}#{str[first_occurence..-1].gsub('1','0')}"
I assume there is some clever regexp for this, but not sure what that would be.
Upvotes: 0
Reputation: 4022
You could replace all the ones with zeros and then change the character you want to keep:
test = "011010010"
testIndex = test.index("1")
test.gsub!("1", "0")
test[testIndex] = "1"
Upvotes: 2
Reputation: 8777
One approach would be to create a new string with all 0
values, of the same length of the original string, and then replacing the first index with a 1
:
str = "011010010"
first_one = str.index("1")
str = "0" * str.length
str[first_one] = "1"
puts str
#=> 010000000
Upvotes: 1