我正在尝试创建一种方法,该方法将采用两个字符串并返回一个字符串,该字符串已将字符串 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 "
我只能使用循环、基本字符串方法(.length()、.charAt())、基本 StringBuilder 方法和字符方法来执行此操作,但我遇到了严重的困难。
现在这是我的代码
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();
}
对于第一个示例,它返回“一个很酷的编程项目”,而对于第二个示例,它返回“一个实际上是两个而不是三个的答案”。我知道这个方法有问题,但我似乎不知道问题出在哪里。感谢任何有关修复代码的帮助。
最佳答案
我认为您到目前为止编写的代码不必要地复杂。使用 String 方法
,而不是循环遍历字符串查找左括号和右括号String.indexOf(char c)
查找括号的索引。这样您就不必循环第一个字符串。如果您无法使用此方法,请告诉我,我可以尝试提供更多帮助。
关于java - 使用字符串和循环创建方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19350484/