java - Replace / Censored -
i'm working system called quiz ...
the last thing remains 'clues'. in present have
<id value="100"> <question value="who said e=mc2"/> <answear value="einstein"/> <clue1 value="e*******"/> <clue2 value="e******n"/> <clue3 value="ei****in"/> </id>
and want remove xml clues because hard them manually ... made failed
public class test { public static void main(string[] argv) throws exception { system.out.println(replacesubstring("einstein", "*", 3)); } static string[] letters = {"e","i"}; public static string replacesubstring(final string str, final string newtoken, int max) { if ((str == null) || (newtoken == null)) return str; stringbuffer buf = new stringbuffer(str.length()); int start = 0, end = 0; for(int = 0; < letters.length; i++) { if(rnd.get(100) > 50) //50% add symbol { while ((end = str.indexof(letters[i], start)) != -1) { buf.append(str.substring(start, end)).append(newtoken); start = end + 1; if (--max == 0) break; } } } buf.append(str.substring(start)); return buf.tostring(); } }
compile result => 'einst*in'
the loop doesn't work.. idk .. first letter array replaced...
if offers me grateful..
-thanks !
how this?
public string generatclue(string answer,int level){ if(level >= answer.length()/2) return answer.replaceall("[^ ]","*"); return answer.substring(0,level) + answer.substring(level,answer.length()-level).replaceall("[^ ]","*") + answer.substring(answer.length()-level); }
output:
generateclue("einstein",1); => e******n generateclue("einstein",3); => ein**ein generateclue("einstein",4) => einstein generateclue("hans christian andersen",4) => hans ********* ****rsen
edit: here's 1 random characters in string:
public string generatclue2(string answer,int level){ if(answer.length()==level) return answer.replaceall("[^ ]","*"); random rand=new random(); for(int i=0; i<level; ++i){ char c; int n; do{ n=rand.nextint(answer.length()); c=answer.charat(n); } while(c == ' ' || c == '*'); answer = answer.substring(0,n) + '*' + answer.substring(n+1); } return answer; }
output:
generateclue2("hans christian andersen",4); => han* c*ri*tian ande*sen generateclue2("hans christian andersen",4); => *ans chr*sti*n an*ersen generateclue2("hans christian andersen",17); => h**s ******i** ***e**** generateclue2("hans christian andersen",23); => **** ********* ********
Comments
Post a Comment