如何通过将下划线替换为另一个字符串中的字符来合并包含下划线的字符串。这个函数来自于我正在制作的一个套接字绞刑器游戏
ie鸡肉:
c__c___
__i____
我的当前代码做到了:c__c_i____
期望的结果: c_ic___
我尝试过使用.replaceall(),但是它在字母重叠的单词中出现了错误
public static void strip(String input){
String newBlank = "";
for(int i = 0; i < word.length(); i++){
if (word.charAt(i) == input.charAt(0)){
newBlank += input.charAt(0);
} else if(blank.contains(word)){
newBlank += guess.charAt(i);
} else {
newBlank += '_';
}
}
//Had replace all here
blank = newBlank.replace("_", "");
如果我有像‘blank = newBlank.replace("_", "");
’这样的工作单词,因为它彼此之间有两个字母'pp‘,但是像blank = newBlank.replace("_", "");
这样的单词最终变成了'cchiken’。
发布于 2020-05-01 12:29:45
String str1 = "c__c___";
String str2 = "__i____";
StringBuilder output = new StringBuilder();
for (int i=0; i<Math.max(str1.length(), str2.length()); i++) {
char ch1 = str1.length() >= i ? '_' : str1.charAt(i);
char ch2 = str2.length() >= i ? '_' : str2.charAt(i);
char result;
if (ch1 == '_')
result = ch2;
else
result = ch1;
output.append(result);
}
发布于 2020-05-01 12:34:41
注意:以提问者明显的专业水平为目标。
伪代码是这样做的一种方式:
let length = max(length of input1, length of input2)
let output = new char[length]
for values of i from 0 to length {
if input1[i] != '_'
output[i] = input1[i] // non-underscore from input1
else
output[i] = input2[i] // non-underscore or underscore
return output converted to array
如果input1
和input2
的长度不同,则需要在if
条件中添加代码,以防止出现数组超出范围的错误。
有许多方法可以将这种伪代码改编成Java;从您已经知道的构造字符串或字符列表的任何一种方法开始。我可以看到使用Streams的一种很好的方式,但这是为更高级的Java程序员准备的。试着用不同的方法玩得开心。
https://stackoverflow.com/questions/61542367
复制相似问题