2017-07-06 104 views
-4

我有兩個字符串,我想在那裏不匹配情況的指標:字符串匹配指數

str = "abcdef" 
str2 = "abddef" 

Output: 2 

因此,誰能告訴我,有沒有在Java中內置函數來獲得指標?如果不是,有人可以給我一個提示嗎?謝謝!

+4

首先要記住,Java中的索引是從* zero *開始的,所以你的例子中的索引應該是'2'而不是'3'。 –

+3

你有沒有嘗試過自己?這是如何工作,或不工作?請花一些時間[採取SO旅遊](http://stackoverflow.com/tour),然後[閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask) ,當然還要學習如何創建[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+0

[在Java中提取兩個字符串之間的差異]的可能重複(https://stackoverflow.com/questions/18344721/extract-the-difference-between-two-strings-in-java) – Pethor

回答

0
String str = "hello"; 
    String str2 = "helll"; 
    int indexDif = -1; 
    for(int i=0; i<str.length(); i++) 
     if(str.charAt(i) != str2.charAt(i)) 
     { 
      indexDif = i; 
      break; 
     } 

假設此時串是相同的長度

0

這裏是關於如何問題可以解決一步步描述。我認爲要實現它的功能:

  1. 第一把手其中字符串equal的情況。如果是,請返回適當的值。

  2. 接下來,找到最短字符串的長度。

  3. 然後for遍歷最短字符串的長度,比較字符串的第i個字母。返回找到的任何不匹配的索引。

  4. 如果沒有發現不匹配,則返回較短字符串的長度。

提示:String類的.length().equals().charAt()方法將是有益的。

0
public static int myCompare(String s1, String s2){ 
    int counter = 0; 
    while (s1.length() > counter && s2.length() > counter){ 
     if (s1.charAt(counter) == s2.charAt(counter)) 
     counter++; 
     else 
     return counter; 
    } 

    if (counter < s1.length() || counter < s2.length()) 
     return counter; 
    else 
     return -1; 
    } 

如果他們等於返回-1,否則0-索引在那裏被發現不匹配。