File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String matching issue.

 
peter cooke
Ranch Hand
Posts: 317
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47258
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 317
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the method below may help you

public int compareTo(String anotherString)
 
Campbell Ritchie
Sheriff
Pie
Posts: 47258
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 47258
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic