java - 使用字符串和循环创建方法

标签 java string loops stringbuilder

我正在尝试创建一种方法,该方法将采用两个字符串并返回一个字符串,该字符串已将字符串 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/

相关文章:

Java如何根据另一个复选框是否已被选中来启用和禁用复选框

java - 不理解模数的工作原理(Eclipse)

java - 为什么 String 的 replaceAll() 方法第一次性能成本高,下一次速度更快?

r - 用利率向量计算复利

c - 我怎样才能在C中继续这个循环

javascript - jQuery 循环内嵌套函数的效率

java - 方法重写中父类(super class)方法之前的抽象关键字

java - 堆栈、括号匹配

java - 如何对字符串应用掩码?

c# - 将字符串转换为 Short