java - Replace character in multiple index -


i have string like:

ab524d000000000000231200000001d0000000000000000524 

the length of string 50. above string one. type of string may have lenght 250 ie. 5 string example:

ab524d000000000000231200000001d0000000000000000524ab524d000000000000231200000001d0000000000000000524ab524d000000000000231200000001d0000000000000000524ab524d000000000000231200000001d0000000000000000524ab524d000000000000231200000001d0000000000000000524. 

now requirement need change d c.

i used following code replace 1 string:

string code = key.substring(0, 2); string currency = key.substring(2, 5); string type = key.substring(5, 6); string amount = key.substring(6, 22); string rate = key.substring(22, 30); string type2 = key.substring(30, 31); string ramount = key.substring(31, 47); string currency2 = key.substring(47, 50);   string finalreq = code + currency + "c" + amount + rate + "c" + ramount + currency2; 

i got following output:

ab524c000000000000231200000001c0000000000000000524 

this 1 string mean 50 length string. string length may 0-250 (string 1 5) pattern same : ab524d000000000000231200000001d0000000000000000524.

which best logic fulfill requirement ?.

note: can not string.replaceall('d','c') because zeroth , first index has character mean may have d.

i

replaceall("\\g(.{5})d(.{24})d(.{19})", "$1c$2c$3") 

should trick don't know if string contain data in format described or if want replace d or character can in places d is.


replaceall uses regex first parameter, , string can use results of regex second parameter. in regex

  • . dot represents character except new line
  • .{x} represents series of characters length x .{3} can match abz or 1x9,
  • regex inside parenthesis (...) create group, , each group has unique number. number can used later example in replacement string via $x x number of group
  • so (.{5})d(.{24})d(.{19}) match 5 characters (and store them in group 1), d 24 characters (and create store them in group 2) d , lastly 19 characters (and store them in group 3)
  • in replacement "$1c$2c$3" use strings ware matched in first group, instead of d put c include match group 2, again instead of d put c , after include last part of match (last 19 characters after second d stored in group 3)
  • also assure match done every 50 characters start of string add \\g represents start of string or match (so there can't characters between previous match , current match).

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -