2

我不知道如何在我的程序运行时用字符串替换字符串。这甚至可能吗?在程序运行时,我想用另一个词替换一个词,然后从该行继续运行。

我怎么能这样做?谢谢大家

hstring.replace("picstart", "up1");
g.drawPixmap(Assets.picstart , 128, 160);
4

3 回答 3

3

你的代码看起来像这样。

if (condition) {
    g.drawPixmap(Assets.picstart , 128, 160);
} else {
    g.drawPixmap(Assets.up1 , 128, 160);
}
于 2013-01-24T20:13:15.977 回答
1

不要使用反射。假设您的资产代码处理您的图像、纹理或任何情况:

String hstring = "picstart";
// ... stuff happens
// that forces us to change hstring! ...
hstring = hstring.replace("up1"); // or you could just say hstring = "up1";
g.drawPixmap(Assets.getAssetFor(hstring), 128, 160);

然后在您的静态资产类中,您可以拥有:

public PixelMap getAssetFor(String identifier) {
     if (identifier.equals("picstart") {
         return new PicStartPixelMap();
     }
     else if (identifier.equals("up1")) {
         return new UpOnePixelMap();
     }
}
于 2013-01-24T20:16:08.013 回答
1

String是不可变的,这意味着您必须将结果分配给变量:

hstring = hstring.replace(...);
于 2013-01-24T20:11:26.950 回答