Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String index of Difference between two Strings

I have two String Lists just like below:

List1 (Generated by sql resultset)

10001
10100
10001

List2 (Generated by sql resultset)

10000
10000
10000

Button Action;

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            // TODO add your handling code here:
            createList1();
            createList2();
            difference();
        } catch (Exception ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }       
    }    

difference void;

public void difference (){
       int minLen = Math.min(List1.get(0).length(), List2.get(0).length());
        for (int i = -1 ; i != minLen ; i++) {
          char chA = List1.get(0).charAt(i);
          char chB = List2.get(0).charAt(i);
        if (chA != chB) {
        System.out.println(chA);
        }
       }  
    }

I want to find which index numbers are different in List1 for index 0.

Thanks in advance.

like image 769
Black White Avatar asked Jun 16 '26 05:06

Black White


1 Answers

Make a loop that iterates the index i from zero the length of the shorter of the two strings, and compare characters one by one, using the == operator:

int minLen = Math.min(a.length(), b.length());
for (int i = 0 ; i != minLen ; i++) {
    char chA = a.charAt(i);
    char chB = b.charAt(i);
    if (chA != chB) {
        ...
    }
}

Before starting the comparison you need to check that a and b are not null. Otherwise, getting the length is going to trigger a null reference exception.

like image 125
Sergey Kalinichenko Avatar answered Jun 18 '26 20:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!