2016-03-09 46 views
0

问题是: 客户帐户是使用代码(例如MA400)在分类系统下提交的。我需要一种将原始MA400重置为更新代码(如MA400.4)的方法。如果新代码有5个字符被重置,则该方法返回true。不是最好的措辞,但这是我现在所拥有的一切。如何比较两个不同长度的字符串以找到相同的子字符串

它还没有被指定,如果字符需要在同一顺序,例如。

String str = "abc123"; 
    String newStr = "xyz123abc"; 

我假设他们需要以相同的顺序。所以上面的字符串只会有3个相似的字符。

char[]array = str.toCharArray(); 
    char[]array2 = newStr.toCharArray(); 

我现在正在考虑使用compareTo方法对两个数组,但我不知道如何做到这一点正是工作。也许我可以使用for循环来停止在最短字符串中的最后一个元素之后进行比较,但不能完全确定我是否可以用它做很多事情。

我觉得我正在以错误的方式解决这个问题,并且有一种较简单的方法来检查字符串中的相似字符?

+1

你真的想要什么? –

+0

命令是否重要?根据这个问题,这个问题可能会非常非常困难。 – dasblinkenlight

+1

“AAAAB”和“ABBBB”有5个相同的字符或2个? – fabian

回答

2

从我理解的这样的事情会工作。请记住,这只会计算唯一的字符。订单无所谓

public static boolean matchingChar(final String st1, final String st2) { 

     if(st1 == null || st2 == null || st1.length() < 5 || st2.length() < 5) { 
      return false; 
     } 

     //This is if you wish unique characters to be counted only 
     //Otherwise you can use simple int count = 0 
     HashSet<Character> found = new HashSet<Character>(); 

     //found.size() < 5 so the loop break as soon as the condition is met 
     for(int i = 0; i < st1.length() && found.size() < 5; i++) {   
      if(st2.indexOf(st1.charAt(i)) != -1) { 
       found.add(st1.charAt(i)); 
      } 
     } 

     return found.size() >= 5; 
    } 
+0

所以'found.size()'将会是不同的字符数?如果是这样,并且我需要相同的数字,那么我可以像'int equivCharacters = str1.length() - found.size'这样做。 – Maitiu

+0

'count.add(classification.charAt(i));'这显然不正确,为什么?它说int不能被取消引用 – Maitiu

+0

found.size()是相同的字符数。 – ata

相关问题