I want to insert hexadecimal byte for example 0A and 00 in a particular pos开发者_高级运维ition in a given string i.e.,String set="16 10 36 07 02 00 00 00 00 00 00 00 00 00 00 0B 11 B7 93"; i want to insert 0A and 00 in 4th and 5th position of the given string. How can i write a code in java
I've got a quick snippet for you, works fine!
public static String insertAtPos(String input, int pos, String insert) {
return
String.format("%s%s%s%s",input.substring(0, 3 * pos), insert, " ", input.substring(3 * pos, input.length()));
}
Usage:
public static void main(String[] args) {
String set= "16 10 36 07 02 00 00 00 00 00 00 00 00 00 00 0B 11 B7 93";
String s0A = "0A";
String sFF = "FF";
System.out.println(insertAtPos(set, 4, s0A));
System.out.println(insertAtPos(set, 5, sFF));
}
You can do something like this:
String set2 = set.substring(0, 9) + "0A 00 " + set.substring(9);
That will give you 16 10 36 0A 00 07 02 00 00 00 00 00 00 00 00 00 00 0B 11 B7 93
If you want something more general, please explain.
Well, you can't alter the contents of a string itself, but you can change the set
variable to refer to a different string. (Or use a different variable if you want.)
The fact that you want to use hex here it irrelevant really. The "4th and 5th position" just means "after index 9 in the string" given that the index is just characters (each "hex byte" of your string is represented by two hex digits and a space; three characters). So:
set = set.substring(0, 9) + "0A 00 " + set.substring(9);
精彩评论