-3

I have two strings and I want to get the index where the mismatch happens:

str = "abcdef"
str2 = "abddef"

Output: 2

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

Satyam Rai
  • 361
  • 1
  • 3
  • 14
  • 4
    First of all remember that indexes in Java goes from *zero*, so the index in your example should be `2` and not `3`. – Some programmer dude Jul 06 '17 at 07:55
  • 3
    And have you tried anything yourself? How did that work, or not work? Please take some time to [take the SO tour](http://stackoverflow.com/tour), then [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and of course learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Jul 06 '17 at 07:56
  • Possible duplicate of [Extract the difference between two strings in Java](https://stackoverflow.com/questions/18344721/extract-the-difference-between-two-strings-in-java) – thruun Jul 06 '17 at 08:03

3 Answers3

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;
        }

assuming that both of the strings are of same length

lala
  • 21
  • 4
0

Here is a step by step description on how the problem could be solved. I assume that you want to implement it as a function:

  1. First handle the case where the strings are equal. If they are, return an appropriate value.

  2. Next, find the length of the shortest string.

  3. Then for loop over the length of the shortest string comparing the ith letter of the strings. Return the index of any mismatch found.

  4. If no mismatch was found return the length of the shorter string.

Hint: The .length(), .equals() and .charAt() methods of the string class will be useful.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
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;
  }

If they are equal return -1, otherwise the 0-index where it has been found a mismatch.

Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42