我正在尝试创建一个程序,该程序将接受一个字符串并将其反转并用其免费字符替换它。
例如,如果字符串" ATTGCC"输入时,方法reverse_it
应输出" GGCAAT"。
" A"取而代之的是" T"和" T"被" A"取代。 " C"取而代之的是" G"和" G"被" C"。
取代这是我的代码:
class DNA
def initialize (nucleotide)
@nucleotide = nucleotide
end
def reverse_it()
puts nucleotide.reverse.gsub("C", "G").gsub("G", "C").gsub("A", "T").gsub("T", "A")
end
protected
attr_reader :nucleotide
end
dna1 = DNA.new("ATTGCC")
dna1.reverse_it
问题是gsub
替换所有出现的字符,sub
仅替换字符串中第一个字符实例。是否有内置方法使该程序有效?
答案 0 :(得分:5)
您可能正在寻找tr,因此在您的方法中代替public class CarTreeNode : TreeNode
{
// ...plus, clone all the other constructors
public CarTreeNode(CarProperties car) :base(car.name) {
Car = car;
}
private CarProperties _car;
public CarProperties Car {
get { return _car; }
set {
_car = value;
// Let it throw an exception if value was null
base.Text = Car.name;
}
}
}
... snip ...
// Regrettably, TreeNodeCollection.AddRange() is an old-fashioned method
// that takes an array
treeView1.Nodes.AddRange(cars.Select(car => new CarTreeNode(car)).ToArray());
... snip ...
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var ctn = e.Node as CarTreeNode;
// In real life there's no reason you'd ever want to replace any car
// that the user clicks on, but it demonstrates the principle.
ctn.Car = new CarProperties() { name = "Aston Martin Vanquish" };
}
,例如:
gsub
答案 1 :(得分:1)
如果有许多字母对要反转,你可以节省一些打字并减少错误输入的机会,如下所示。
n = 785
,当然还有:
function minMax(items)
{
return [items.reduce((prev, curr)=> Math.min(prev, curr)),
items.reduce((prev, curr)=> Math.max(prev, curr))]
}