我有两个包含一些十六进制值的字符串。
String One = "f9 d4 62 aa f9 d4 62 aa 74 10 99 8b";
String Two = "3c 9c a7 e2 3c 9c a7 e2 b1 58 f9 d4";
请注意,十六进制之间的空格是由将二进制转换为十六进制的函数生成的。此外,十六进制值是成对处理的,例如,f9 d4 被视为一对。
我的问题是 - 如何返回两个字符串中两个相似对的索引(在本例中为子字符串值)? 上面的示例在索引 1 中有 f9 d4,而另一个字符串在索引 6 中有它。所以我希望输出为 (1,6) 和 (3,6)。 任何帮助或建议将不胜感激。
最佳答案
考虑这样的代码:
public static void main(String[] args) {
String One = "f9 d4 62 aa f9 d4 62 aa 74 10 99 8b";
String Two = "3c 9c a7 e2 3c 9c a7 e2 b1 58 f9 d4";
int[] x = convert(One);
int[] y = convert(Two);
for (int i = 0; i < x.length; i++) {
int number = x[i];
int index = find(number, y);
if (index > 0) {
System.out.println("found (" + (i + 1) + "," + index + ")");
}
}
}
private static int find(int number, int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] == number) {
return i + 1;
}
}
return 0;
}
private static int[] convert(String str) {
String[] tokens = str.split("\\s");
int[] result = new int[tokens.length / 2];
for (int i = 0; i < tokens.length; i += 2) {
String hex = tokens[i] + tokens[i + 1];
result[i / 2] = Integer.parseInt(hex, 16);
}
return result;
}
输出:
found (1,6)
found (3,6)
如您所见,convert(str)
方法将每 4 个十六进制数字转换为 1 个整数,并返回此类整数的数组。因此,convert(One) 只是 int[] 等于:
System.out.println(Arrays.toString(x));
[63956, 25258, 63956, 25258, 29712, 39307]
接下来,您可以实现辅助方法 find(),该方法返回在给定数组中找到数字的索引(从 1 开始的索引)。
关于java - 比较两个字符串值并返回其在 java 中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26059239/