Java使用交替字符合并两个字符串,同时保留运行
将两个字符串合并在一起,使用每个字符串中的交替字符,但相同字符的行保持在一起。例如,abcde,xyz返回axbyczde abbcde,xxxyzzz返回axxxbbyczzde 给定下面的代码,我得到的输出是axbxbcydzezzz,这不仅无法保留运行,而且还会添加和删除一些字符。对于我的代码有什么问题,如果能提供一些帮助,我们将不胜感激。先谢谢你Java使用交替字符合并两个字符串,同时保留运行,java,string,merge,Java,String,Merge,将两个字符串合并在一起,使用每个字符串中的交替字符,但相同字符的行保持在一起。例如,abcde,xyz返回axbyczde abbcde,xxxyzzz返回axxxbbyczzde 给定下面的代码,我得到的输出是axbxbcydzezzz,这不仅无法保留运行,而且还会添加和删除一些字符。对于我的代码有什么问题,如果能提供一些帮助,我们将不胜感激。先谢谢你 public class Test { public static void main(String[] args) {
public class Test {
public static void main(String[] args) {
String t = "abbcde";
String s = "xxxyzzzz";
String result = "";
char tcurrent = t.charAt(0);
char scurrent = s.charAt(0);
result += tcurrent;
result += scurrent;
int i = 1;
int j = 1;
while (i < t.length() && j < s.length()) {
if (tcurrent == t.charAt(i)) {
result += t.charAt(i);
i++;
}
if (scurrent == t.charAt(j)) {
result += s.charAt(j);
j++;
} else {
tcurrent = t.charAt(i);
scurrent = s.charAt(j);
result += t.charAt(i);
result += s.charAt(i);
i++;
j++;
}
}
while (i < t.length()) {
result += t.charAt(i);
i++;
}
while (j < s.length()) {
result += s.charAt(i);
j++;
}
System.out.println(result);
}
}
首先,当您执行result+=scurrent时,开始时出现问题;未首先检查t.charAt1和以下内容 此外,还有一个复制粘贴错误: 如果scurrent==t.charAtj->则应为s.charAtj 最后,末尾的另一个复制粘贴错误:result+=s.charAti->应该是charAtj 从概念上讲,你做错的是一直在s和t之间交替。相反,您应该一次只检查一个字符串,并运行while循环,直到遇到不同的字符:
public static void main(String[] args) {
String t = "abbcde";
String s = "xxxyzzzz";
String result = "";
int tNextIndex = 0;
int sNextIndex = 0;
/* alternate while both strings have characters left */
while (tNextIndex < t.length() && sNextIndex < s.length()) {
char tPreviousChar = t.charAt(tNextIndex++);
result += tPreviousChar;
while (tNextIndex < t.length() && t.charAt(tNextIndex) == tPreviousChar){
result += tPreviousChar;
tNextIndex++;
}
char sPreviousChar = s.charAt(sNextIndex++);
result += sPreviousChar;
while (sNextIndex < s.length() && s.charAt(sNextIndex) == sPreviousChar){
result += sPreviousChar;
sNextIndex++;
}
}
/* if either of the string was finished, add the remainder of the other one to the result */
while (tNextIndex < t.length()) {
result += t.charAt(tNextIndex++);
}
while (sNextIndex < s.length()) {
result += s.charAt(sNextIndex++);
}
System.out.println(result);
}
好吧,如果你是一个模式和匹配的球迷,这将工作-相当缓慢
O/p:
你试过调试这个吗?步骤1。调试它。找到它断裂的地方。第二步。如果您仍然不知道如何解决问题,请编辑您的问题并告知我们。第三步。一般来说,试着在代码中添加一些注释,看看这些东西应该做什么。当你在某个地方出错时,当你在写a-b的同时从b中减去a时,更容易看到它。
public static void main(String[] args) {
String s1 = "abbcde";
String s2 = "xxxyzzzz";
Pattern p = Pattern.compile("(\\w)\\1*");
Matcher m1 = p.matcher(s1);
Matcher m2 = p.matcher(s2);
StringBuilder sb = new StringBuilder();
int start = -1;
while (m1.find() && m2.find()) {
sb.append((m1.group() + m2.group()));
start = m1.end();
}
m1.reset(s1.substring(start, s1.length()));
while (m1.find()) {
sb.append(m1.group());
}
while(m2.find()) {
sb.append(m2.group());
}
System.out.println(sb);
}
axxxbbyczzzzde