我正在尝试创建一种方法,该方法将采用两个字符串并返回一个字符串,该字符串已将字符串 1 中括号之间的单词替换为字符串 2 中括号中的单词,但我遇到了我似乎无法理解的问题。举个例子
replaceText("a (simple) programming (example)", "(cool) (problem)")
应该返回
"a cool programming problem"
和
replaceText("a ((nested) example) with (three) replacements (to (handle))",
"the replacements are (answer) and (really (two) not three)")
应该返回
"an answer with really (two) not three replacements "
我只能使用循环、基本的 String 方法(.length()、.charAt())、基本的 StringBuilder 方法和 Character 方法,但我遇到了严重的困难。
现在这是我的代码
public class loopStringAnalysis {
public static String replaceText (String s1, String s2){
StringBuilder newStringBuild = new StringBuilder ();
int count = 0;
int count1 = 0;
for (int i = 0, i1 = 0; i < s1.length() && i1 < s2.length(); i = i + 1){
if (s1.charAt(i) == '(')
count = count + 1;
else if (s1.charAt(i) == ')')
count = count - 1;
else if (count == 0)
newStringBuild.append(s1.charAt(i));
else if (count != 0){
while (count1 == 0) {
if (s2.charAt(i1) == '(')
count1 = count1 + 1;
else if (s2.charAt(i1) == ')')
count1 = count1 - 1;
i1 = i1 + 1;
}
while (count1 != 0) {
if (s2.charAt(i1) == '(')
count1 = count1 + 1;
else if (s2.charAt(i1) == ')')
count1 = count1 - 1;
else if (count1 != 0)
newStringBuild.append(s2.charAt(i1));
i1 = i1 + 1;
}
while (count != 0) {
if (s1.charAt(i) == '(')
count = count + 1;
else if (s1.charAt(i) == ')')
count = count - 1;
i = i + 1;
}
}
}
return newStringBuild.toString();
}
对于第一个示例,这将返回“一个很酷的编程项目”,而对于第二个示例,这将返回“一个答案,实际上是两个而不是三个”。我知道这种方法有问题,但我似乎不知道在哪里。感谢您对修复代码的任何帮助。