gpt4 book ai didi

java - 部分比较 2 个字符串

转载 作者:行者123 更新时间:2023-11-30 06:13:42 26 4
gpt4 key购买 nike

我有一个带有 GUI 的程序,在其中插入几个十六进制(字符串),按下搜索按钮,然后找到它的代码。我从 CSV 文件导入我有代码的所有十六进制。我想要的是,如果我输入例如:11 D7 E2 FA,我的程序将只搜索第二个半字节,x意味着忽略:x1 x7 x2 xA,如果它在 CSV 中找到类似的内容,它会给我它的代码。这就是我到目前为止所拥有的,这只会找到字符串匹配时的情况。

codeOutputField.setText("");
String input = hexEntryField.getText();

try {
br = new BufferedReader(new FileReader(FIS));
while ((line = br.readLine()) != null) {
code = line.split(csvSplitBy);
if (input.equals(code[0])) {
codeOutputField.setText(code[1]);
}
}
}

示例 CSV:

01 5F 1E CE,0055
01 5F 13 D0,0062
01 5E 36 FE,0101
00 5E 36 FF,1002

这是现在适合我的代码,想分享它。我现在唯一的问题是我只能从 bat 文件运行 jar 文件,双击不起作用。我不知道为什么。

String input = hexEntryField.getText();
String[] myStringArray = input.split("");

codeOutputField.setText("");

try {
br = new BufferedReader(new FileReader(FIS));
while ((line = br.readLine()) != null) {
code = line.split(csvSplitBy);
List<String> items = Arrays.asList(code[0].split(""));
System.out.println(items);

if (myStringArray[1].equals(items.get(1))
&& myStringArray[4].equals(items.get(4))
&& myStringArray[7].equals(items.get(7))
&& myStringArray[10].equals(items.get(10))) {
codeOutputField.setText(code[1]);
}
}
}

最佳答案

您的问题更多是关于解析每一行。我会结合一些正则表达式:

public class Record {
private static final Pattern HEX_VALUE = Pattern.compile("[A-F0-9][A-F0-9]");
//...
public static Record from(String line) throws Exception {
Record record = new Record();
String[] parts = line.split(",");
if (parts.length != 2) {
throw new Exception(String.format("Bad record! : %s", line));
}
record.code = parts[1];
String hexes[] = parts[0].split("\\s");
if (hexes.length != 4) {
throw new Exception(String.format("Bad record! : %s", line));
}
for (String hex: hexes) {
if (!HEX_VALUE.matcher(hex).matches()) {
throw new Exception(String.format("Bad record! : %s", line));
}
}
record.hex1 = hexes[0];
record.hex2 = hexes[1];
record.hex3 = hexes[2];
record.hex4 = hexes[3];
return record;
}
...
@Override
public boolean equals(Object obj) {
boolean ret = false;
if (obj instanceof Record) {
Record r = (Record) obj;
ret = equalsSecondCharacter(this.hex1, r.hex1)
&& equalsSecondCharacter(this.hex2, r.hex2)
&& equalsSecondCharacter(this.hex3, r.hex3)
&& equalsSecondCharacter(this.hex4, r.hex4);
}

return ret;

}
...

然后只需搜索记录列表即可。在示例中,我使用了 Apache Commons Collections 过滤:

while((line = br.readLine()) != null) {
records.add(Record.from(line));
}
// Check into the list
Collection<Record> filtered =
CollectionUtils.select(records, new EqualPredicate<Record>(inputRecord));
System.out.println("Results:");
for (Record rec: filtered) {
System.out.println(rec);
}

希望您觉得它有用。

关于java - 部分比较 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49689992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com