我正在尝试从字符串中删除非数字字符。
我尝试使用 .replace()
方法,但返回错误:
The method replace(char, char) in the type String is not applicable for the arguments (String, String)
代码:
Properties p = new Properties();
File f = new File("coords.txt");
if (f.exists()) {
FileInputStream in;
try {
in = new FileInputStream(f);
p.load(in);
in.close();
} catch (Exception e) {
System.err.println("Failed to load coordinates");
System.err.println(e.getMessage());
Button.waitForAnyPress();
System.exit(0);
}
} else {
System.out.println("No coordinates found");
while (!Button.ESCAPE.isPressed()) {
Thread.yield();
}
System.exit(0);
}
当我打印出字符串gg
时,初始化如下:
String gg = p.toString();
我得到输出:Object020f458
。
我的计算机在替换时突出显示错误:
gg = gg.replace("{", "");
gg = gg.replace("=", "");
gg = gg.replace("}", "");
int commaLoc = gg.indexOf(",");
int x = Integer.parseInt(gg.substring(0,commaLoc));
int y = Integer.parseInt(gg.substring(commaLoc + 1));
最佳答案
所以我正在研究 NXT 及其 API ( JavaDocs )
顺便说一句,我猜我绝不是 NXT 和 leJOS 方面的专家。
您可以通过 JavaDoc 看到 replace(CharSequence, CharSequence)
方法不存在。
虽然我不会以这种方式解决问题,但您可以尝试使用 StringBuilder
删除不需要的字符。
例如,请参阅 Jon Skeet 的回答以获取想法 https://stackoverflow.com/a/3472705/1392277
您可以提取如下方法:
private String removeChars(
final String originalString,
final String charsToRemove) {
final StringBuilder stringBuilder = new StringBuilder(originalString);
int i = stringBuilder.indexOf(charsToRemove);
while (i != -1) {
stringBuilder.replace(i, i + charsToRemove.length(), "");
i = stringBuilder.indexOf(charsToRemove, i);
}
return stringBuilder.toString();
}
关于java - String .replace() 不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619158/