2016-03-09 50 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

相關問題