java - Need the explanation of code of string replacement using String buffer -


I got the following code from the site, but I can not understand it clearly whether someone helps me understand the code ? Replaces the code string. It replaces Strontotopelease with the replacement string. This character is substituting but I could not understand its detail.

  string strain = "al% hand% receivable number%% exam% is correct."; String stringolailease = "% return number%"; String replacement string = "12345"; String replaced string = null; Int idx = strIn.lastIndexOf (stringToReplace); If (idx! = -1) {stringbuffer result = new stringbuffer (strIn); Results.replace (idx, idx + stringToReplace.length (), substitution string); While ((idx = strIn.lastIndexOf (stringToReplace, idx-1)) -1) {results.replace (idx, idx + stringToReplace.length (), substitution string); } // system.out.printLN (result.trustring);; ReplacedString = results.toString (); } System.out.println (Replaced string);   

Output is

  Al% hand 12345% exam% has arrived OK.    

First, you have the input string strIn , then Instead of changing stringToReplace and replace string replaceString . Replace strings may be related to replaceString ,

you search for the last occurrence of the string to replace with lastIndexOf < . This gives you the last index, on which the replacement string starts in the original string.

If you got to change the string (if index is not -1), then you use the StringBuffer method to replace the string For idx to idx + stringToReplace.length () (to change the string to its full length, starts with the found index).

Again you can check that the string is still in the result to change, and whenever it happens, you change it.

Then you strip the result (a StringBuffer ) and output it.

Comments

Popular posts from this blog

Pass DB Connection parameters to a Kettle a.k.a PDI table Input step dynamically from Excel -

multithreading - PhantomJS-Node in a for Loop -

c++ - MATLAB .m file to .mex file using Matlab Compiler -