java - Replace reoccurring substring with array values when there are more substrings than values -
public static string updatedstr() { string [] ar= {"green","red","purple","black"}; string str="the colors (blue), (blue), , (yellow). prefer (orange)"; stringbuilder out = new stringbuilder (); int x = 0; int pos = 0; for(int = str.indexof('(', 0); != -1; = str.indexof('(', + 1)) { out.append (str.substring(pos,i)); // add part between last ) , next ( out.append (ar[x++]); // add replacement word pos = str.indexof(')', i) + 1; } out.append (str.substring(pos)); // add part after final ) return out.tostring (); }
i able replace whatever inside parentheses elements string array.
here, achieve output of
"the colors green, red, , purple. prefer black."
now, trying implement scenario string [] ar= {"green","red"}
.
i output
"the colors green, red, , (yellow). prefer (orange)."
as can see, rest of original string remains untouched due there not being enough values replace them.
so far, have tried using while loop before loop prevent arrayindexoutofboundserror
, still getting error.
you need declare new variable counting how many replacements have been made , stop when has reached array length.
public static string updatedstr() { string [] ar= {"green","red"}; string str="the colors (blue), (blue), , (yellow). prefer (orange)"; stringbuilder out = new stringbuilder (); int x = 0; int pos = 0; int added=0; for(int = str.indexof('(', 0); != -1 && added<ar.length; = str.indexof('(', + 1)) { out.append (str.substring(pos,i)); // add part between last ) , next ( out.append (ar[x++]); // add replacement word pos = str.indexof(')', i) + 1; } out.append (str.substring(pos)); // add part after final ) return out.tostring (); }
Comments
Post a Comment