gpt4 book ai didi

java - 替换/审查

转载 作者:行者123 更新时间:2023-12-01 19:19:25 27 4
gpt4 key购买 nike

我正在开发一个名为 Quiz 的系统...

最后剩下的就是“线索”。目前我有

   <id value="100"> 
<question value="Who said E=mc2"/>
<answear value="Einstein"/>
<clue1 value="E*******"/>
<clue2 value="E******n"/>
<clue3 value="Ei****in"/>
</id>

我想从 xml 中删除线索,因为很难手动完成它们......所以我做了一些事情,但失败了

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 i = 0; i < letters.length; i++)
{
if(Rnd.get(100) > 50) //50% to add the 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();
}
}

编译结果 => 'Einst*in'

循环不起作用..idk..仅替换数组中的第一个字母...

如果有人愿意帮助我,我将非常感激..

-谢谢!

最佳答案

像这样怎么样?

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);
}

输出:

generateClue("Einstein",1);
=> E******n
generateClue("Einstein",3);
=> Ein**ein
generateClue("Einstein",4)
=> Einstein
generateClue("Hans Christian Andersen",4)
=> Hans ********* ****rsen

编辑:这是字符串中随机字符的一个:

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;
}

输出:

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);
=> **** ********* ********

关于java - 替换/审查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5041891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com