string comparison
Java programming
substring removal
coding tutorial
software development

Compare strings in java and remove the part of string where they are identical

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When two Java strings share the same beginning or ending, a common task is to trim the identical part and keep only the differing part. The important first step is to define what "identical part" means, because removing a common prefix is very different from removing any matching characters anywhere in the string.

Remove a Common Prefix

The most common interpretation is "remove the shared prefix." That means comparing both strings from left to right until the first mismatch.

Here is a small utility that returns the remaining unmatched parts:

java
1public class StringDiff {
2    public record Result(String leftRemainder, String rightRemainder) {}
3
4    public static Result removeCommonPrefix(String left, String right) {
5        int max = Math.min(left.length(), right.length());
6        int index = 0;
7
8        while (index < max && left.charAt(index) == right.charAt(index)) {
9            index++;
10        }
11
12        return new Result(left.substring(index), right.substring(index));
13    }
14
15    public static void main(String[] args) {
16        Result result = removeCommonPrefix("abcXYZ", "abcDEF");
17        System.out.println(result.leftRemainder());
18        System.out.println(result.rightRemainder());
19    }
20}

The output is:

text
XYZ
DEF

This works because both strings share the prefix "abc", so that part is removed from both.

Remove a Common Suffix

Sometimes the identical part is at the end rather than the beginning. In that case, scan from right to left.

java
1public static StringDiff.Result removeCommonSuffix(String left, String right) {
2    int leftIndex = left.length() - 1;
3    int rightIndex = right.length() - 1;
4
5    while (leftIndex >= 0
6            && rightIndex >= 0
7            && left.charAt(leftIndex) == right.charAt(rightIndex)) {
8        leftIndex--;
9        rightIndex--;
10    }
11
12    return new StringDiff.Result(
13            left.substring(0, leftIndex + 1),
14            right.substring(0, rightIndex + 1));
15}

If the inputs are "report-final.txt" and "image-final.txt", the common suffix is "-final.txt", so the remaining parts are "report" and "image".

This is a different problem from prefix trimming, so it deserves a separate method rather than overloading one function with unclear behavior.

When You Need More Than Prefix or Suffix Matching

If you want to remove matching characters in the middle of both strings, the problem becomes more complex. For example, removing the longest common subsequence is not the same as trimming a prefix or suffix. That requires a different algorithm entirely.

For many business cases, prefix trimming is enough. Common examples include:

  • removing a shared file path root
  • stripping a common namespace prefix
  • comparing version strings after a shared start

When the task is really "find the first position where they differ," a prefix-based solution is the right one and stays easy to reason about.

A Reusable Comparison Utility

If you want a single helper for debugging or comparison features, you can make the result more explicit:

java
1public class PrefixComparison {
2    public record Comparison(String commonPrefix, String leftOnly, String rightOnly) {}
3
4    public static Comparison compare(String left, String right) {
5        int max = Math.min(left.length(), right.length());
6        int index = 0;
7
8        while (index < max && left.charAt(index) == right.charAt(index)) {
9            index++;
10        }
11
12        return new Comparison(
13                left.substring(0, index),
14                left.substring(index),
15                right.substring(index));
16    }
17
18    public static void main(String[] args) {
19        Comparison comparison = compare("user:12345", "user:99887");
20        System.out.println("Common: " + comparison.commonPrefix());
21        System.out.println("Left: " + comparison.leftOnly());
22        System.out.println("Right: " + comparison.rightOnly());
23    }
24}

This style is useful because it keeps the removed part visible instead of discarding it immediately. In debugging tools and diff views, that extra context is often more useful than only returning the remainders.

Common Pitfalls

The biggest mistake is not defining the match rule clearly. Shared prefix, shared suffix, longest common substring, and longest common subsequence are different problems with different algorithms.

Another common issue is forgetting edge cases. Empty strings, one fully matching string, or no common prefix at all should all return sensible results without throwing exceptions.

Case sensitivity also matters. Java String comparison is case-sensitive by default, so "ABC" and "abc" do not share a common prefix unless you normalize them first.

Finally, be careful with Unicode text if your application works at the user-visible character level. charAt operates on UTF-16 code units, which is usually fine for ASCII-like data but can be surprising for some Unicode characters.

Summary

  • For most cases, "remove the identical part" means trimming a common prefix or suffix.
  • A left-to-right scan solves common-prefix removal in linear time.
  • A right-to-left scan solves common-suffix removal.
  • Do not use prefix logic for middle-string matching problems such as longest common subsequence.
  • Define the exact comparison rule before writing the code.

Course illustration
Course illustration

All Rights Reserved.