wood burning stoves 2.0*
The moose likes Java in General and the fly likes String matching issue.  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String matching issue.  " Watch "String matching issue.  " New topic
Author

String matching issue.

peter cooke
Ranch Hand

Joined: Mar 16, 2004
Posts: 314
Given 2 String objects

I need to determine at what charcater they differ. It's not a string regex. Oh java 5 solutions are possible.

String 1) Foobar
String 2) Foodoo

would differ at character 4

String 1) Foobar
String 2) Belair
would differ at charater ZERO.

Any suggestions on how to determine where 2 strings start differeing?


CIAO Peter M. Cooke
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
Split them into a char[] arrsy?
Iterate the array with a while (char1[i] == char2[]) loop?
Put a counter inside the loop?

Would that work?
peter cooke
Ranch Hand

Joined: Mar 16, 2004
Posts: 314
On the way home I thought of that also.
It works but was kinda hoping there was some new java string process class to learn.

Oh well K.I.S.S. it is!
amit pandit
Greenhorn

Joined: Mar 01, 2007
Posts: 23
the method below may help you

public int compareTo(String anotherString)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
the method below may help you

public int compareTo(String anotherString)
Afraid I don't think it will. The way compareTo() seems to work with Strings is that it subtracts the numbers of the first letters or characters which differ.
Find an ASCII chart and you will see that, A=41, B= 42, C=43, D=44 . . . m=6d . . . r=72, z=7a. (All numbers in hex.)
SO: "Campbell".compareTo("David") should return 1 because 'D' - 'C' is 44 - 43 is 1.
"Campbell".compareTo("Carol") should return 'r' - 'm' = 72 - 6d = 5. This does not however distinguish differences at the first position and third position, so I don't think compareTo() actually tells you what you are looking for.

CR
[ March 05, 2007: Message edited by: Campbell Ritchie ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
I have just tried itI did in fact get 1 and 5 . . .
[Campbell@dhcppc0 disk]$ java StringDifferenceTest
"Campbell".compareTo("David") is -1
[Campbell@dhcppc0 disk]$ java StringDifferenceTest Campbell Carol
"Campbell".compareTo("Carol") is -5
. . . only with minus signs.
CR
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String matching issue.