Comparing strings and get the first place where they vary from eachother

后端 未结 8 1145
滥情空心
滥情空心 2020-12-16 11:07

I want to get the first place where 2 string vary from each other. example: for these two strings: \"AAAB\" \"AAAAC\"

I want to get the result 4.

How do i d

8条回答
  •  误落风尘
    2020-12-16 12:01

    int compare( String a, String b ){
    
       for( int i = 0; i < min( a.length, b.length ); i++ ){
    
          if( a.getCharAt(i) != b.getCharAt(i) ){
             return i;
          }
    
      }
    
      return -1; //a contained in b, or b contained in a
    
    } 
    

    The code above doesn't check anything like nulls, etc.

提交回复
热议问题