【问题标题】:Compare two string on their shift比较两个字符串的班次
【发布时间】:2012-03-26 12:08:06
【问题描述】:

一、代码:

String account1= "0000180000";
String account2= "0000000180";
int i = 0;
int j = 0;

for (; i < account1.length() -1; i++ ) {
   char test1 = account1.charAt(i);
   while (test1 != '0') {
      System.out.println(i);
      break;
   }
}

for (; j < account2.length() -1; j++) {
   char test2 = account2.charAt(j);
   while (test2 != '0') {
      System.out.println(j);
      break;
   }
}

if (i > j) {
   int res = i-j;
   System.out.println(res);
} else {
   int res = j-i;
   System.out.println(res);
}

作为移位的结果,我得到 0,而不是 3。

我在代码中做错了什么?有人可以帮我吗?

【问题讨论】:

  • 你的意思是移位还是轮换?
  • 谢谢约翰,我可以通过 i 和 j 找出发生变化的索引。
  • @hamadakarim 你能接受你得到的最佳答案吗?

标签: java string shift


【解决方案1】:

我认为你应该用 if 替换你的 while。 while 中的 break 意思是:退出当前循环,也就是 while 本身,但我猜你想退出 for。

【讨论】:

    【解决方案2】:

    break 只会让您脱离while 循环,而不是for

    我想你可能是想说:

    if (test1 != '0'){
        System.out.println(i);
        break;
    }
    

    if (test2 != '0'){
        System.out.println(j);
        break;
    }
    

    【讨论】:

      【解决方案3】:

      以下应该是if 而不是while

      while (test1 != '0'){
          System.out.println(i);
          break;
      }
      

      另外这个for (; i &lt; account1.length() -1; i++ )应该是for (; i &lt; account1.length(); i++ )

      【讨论】:

        【解决方案4】:

        如何使用运行时中的许多辅助方法?

        String account1= "0000180000";
        String account2= "0000000180";
        
        String pattern = account1.replaceAll("^0+", "").replaceAll("0+$", "");
        int pos = account2.indexOf( pattern ); // TODO Check this for != -1 to make sure there is a match
        int res = Math.abs( account1.indexOf( pattern ) - pos );
        

        【讨论】:

          猜你喜欢
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-05
          • 2017-07-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多