I wrote a function that finds the difference between two strings. This only works given that the difference is continuous.
Beyond doubt this already exists, I am recreating this for educational purposes. I would like feedback about my performance and efficiency.
Examples of this method:
String difference = Difference("Hello", "Hello world!");
//difference would be " world!"
String difference = Difference("Removing text", "Removi");
//difference would be "ng text"
String difference = Difference("same size", "SAME size");
//difference would be "SAME"
public static String Difference(String string1, String string2)
{
int size = string2.length() - string1.length();
if(size < 0)
{
size *= -1;
String swap = string1;
string1 = string2;
string2 = swap;
}
String difference = "";
int start = DifferenceStartIndex(string1, string2);
if(size > 0)
for(int i = start; i < start + size; i++)
difference += string2.charAt(i);
else
{
if(start != -1)
{
int end = DifferenceEndIndex(string1, string2, start);
for(int i = start; i < end; i++)
difference += string2.charAt(i);
}
else
return "";
}
return difference;
}
public static int DifferenceStartIndex(String string1, String string2)
{
int maxSize = (string1.length() > string2.length()) ? string1.length() : string2.length();
for(int i = 0; i < maxSize; i++)
if(((i < string1.length()) ? string1.charAt(i) : '\0') != ((i < string2.length()) ? string2.charAt(i) : '\0'))
return i;
return -1;
}
public static int DifferenceEndIndex(String string1, String string2, int start)
{
int maxSize = (string1.length() > string2.length()) ? string1.length() : string2.length();
int end = maxSize;
for(int i = start; i < maxSize; ++i)
if(string1.charAt(i) != string2.charAt(i))
end = i + 1;
return end;
}
...under your question title. Try to explain first than paste in the code in future. \$\endgroup\$string2is somewhere in the middle ofstring1, is that situation expected? For example, "Removing stuff" and "moving". \$\endgroup\$