Advertisement
DulcetAirman

compare first n symbols

Apr 17th, 2018
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package ch.fhnw.claudemartin;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class SomeClass {
  6.   public static void main(final String[] args) {
  7.     test("", "", true);
  8.     test("12345", "12345", true);
  9.     test("abcdefg", "abcdefg", true);
  10.     test("abcdeXX", "abcdeYY", true);
  11.     test("xzy", "abc", false);
  12.     test("xzy", "abcde", false);
  13.     test("a", "A", false);
  14.     test("12345", "12345X", true);
  15.  
  16.     // one symbol in two chars (surrogate pair):
  17.     String clef = "\uD834\uDD1E";
  18.     clef = clef + clef + clef + clef + clef + clef;
  19.     test(clef, clef + clef, true);
  20.  
  21.     // Combination with diacritical mark (acute):
  22.     // this might have to fail. requirements unclear.
  23.     test("é", "e\u0301", true);
  24.   }
  25.  
  26.   static void test(final String a, final String b, final boolean expected) {
  27.     final boolean actual = equalFirst5(a, b);
  28.     (actual == expected ? System.out : System.err)
  29.         .format("'%s' / '%s' = %s%n", a, b, actual);
  30.   }
  31.  
  32.   public static boolean equalFirst5(final String a, final String b) {
  33.     return equalFirstN(a, b, 5);
  34.   }
  35.  
  36.   public static boolean equalFirstN(final String a, final String b, final int n) {
  37.     if (a == b)
  38.       return true;
  39.     final int[] ia = a.codePoints().limit(n).toArray();
  40.     final int[] ib = b.codePoints().limit(n).toArray();
  41.     return Arrays.equals(ia, ib);
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement