如何替换目标数组字符串并将其更改为用户输入字符串



所以基本上我是stackoverflow的新手。我有这样的代码,它将每个下划线替换为用户字符串。

public class MainActivity extends AppCompatActivity {
private String result="";
private String textresult = "The red fox jumps over the lazy dog";
EditText text;
Button btn;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.editText);
btn = findViewById(R.id.button_edittext);
final TextView tvtext = findViewById(R.id.result);
final String les = textresult.replaceAll("[a-z]", "_");
tvtext.setText(les);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v
String les1 = textresult.replaceAll("[a-z]", "_");
final String sampleText = text.getText().toString().trim();
int noOfBtns = sampleText.length();
int noOftext = les1.length();

final TextView[] btns = new TextView[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] =   new TextView(MainActivity.this);
btns[i].setText(sampleText.substring(i,i+1));
result = result+btns[i].getText().toString();
char[] c = result.toCharArray();
les1 = changeCharInPosition(i, c[i], les1);*/
tvtext.setText(les1);
}
}
});
}

所以输出是这样的:

**T__ ___ ___ ____ ____ ___ ____ ___.**

问题是:那么我如何才能将文本的第一个长度作为目标,直到文本结束,并更新或替换字符的每个长度,例如:

当用户输入单词并更新或替换时:

**user input: the red
display: the red ___ ____ ____ ___ ____ ___.**

如果用户为单词输入了错误的字母,它将显示*:

**user input: the red fix
display: the red f*x ____ ____ ___ ____ ___.**

此代码急需帮助。非常感谢。

我认为您要做的是根据EditText中的当前用户输入更新所有这些TextViews。在text变量上添加TextWatcher:

text.addTextChangedListener(new TextWatcher(){...

你必须自己弄清楚你需要什么方法的TextWatcher接口。祝你好运

您的示例代码不是JavaScript,但您将问题标记为JavaScript。

所以我给出一个简单的JS答案:(

const text = "The red fox jumps over the lazy dog."
const question = document.getElementById('question')
const guess = document.getElementById('guess')
// handling input
const check = (g, t) => {
const gArr = [...g]
const tArr = [...t]
const r = []
tArr.forEach((e, i) => {
// if the character in the text is ' ' or '.'
// just return it as it is
if (e === ' ' || e === '.') {
r.push(e)
} else if (!gArr[i]) {
// if the quess is shorter than the real text, then
// return _ in not yet quessed places
r.push('_')
} else if (gArr[i]) {
if (gArr[i] === e) {
// if the guess is correct,
// then return the correct guess
r.push(e)
} else {
// if the guess is incorrect,
// then return '*'
r.push('*')
}
}
})
return r.join('')
}
// set the stage
question.innerHTML = check(guess.value, text)
// react to input events
guess.addEventListener('input', function(e) {
const r = check(e.target.value, text)
question.innerHTML = r
})
<label for="guess">Guess the text: <input id="guess" type="text"/></label>
<div id="question"></div>

最新更新