From 14a2ca87dc5fdd5e7b09da274acac8aac5024986 Mon Sep 17 00:00:00 2001 From: iTitus Date: Sat, 23 Oct 2021 16:39:43 +0200 Subject: [PATCH] add some helper methods for text --- .../github/ititus/text/SubCharSequence.java | 57 +++++++++++++++++++ .../java/io/github/ititus/text/TextUtil.java | 21 +++++++ 2 files changed, 78 insertions(+) create mode 100644 src/main/java/io/github/ititus/text/SubCharSequence.java diff --git a/src/main/java/io/github/ititus/text/SubCharSequence.java b/src/main/java/io/github/ititus/text/SubCharSequence.java new file mode 100644 index 0000000..6278e78 --- /dev/null +++ b/src/main/java/io/github/ititus/text/SubCharSequence.java @@ -0,0 +1,57 @@ +package io.github.ititus.text; + +import java.util.Objects; + +public class SubCharSequence implements CharSequence { + + private final CharSequence sequence; + private final int start; + private final int end; + + public SubCharSequence(CharSequence sequence, int start, int end) { + Objects.requireNonNull(sequence); + if (start < 0 || end < 0 || end < start) { + throw new IllegalArgumentException(); + } + + int length = sequence.length(); + if (start > length || end > length) { + throw new IllegalArgumentException(); + } + + this.sequence = sequence; + this.start = start; + this.end = end; + } + + @Override + public int length() { + return end - start; + } + + @Override + public char charAt(int index) { + index += start; + if (index < 0 || index >= end) { + throw new IndexOutOfBoundsException(); + } + + return sequence.charAt(index); + } + + @Override + public CharSequence subSequence(int start, int end) { + start += this.start; + end += this.start; + if (start < 0 || start >= this.end || end < 0 || end >= this.end) { + throw new IndexOutOfBoundsException(); + } + + return new SubCharSequence(sequence, this.start + start, this.start + end); + } + + @Override + public String toString() { + return sequence.subSequence(start, end).toString(); + } +} diff --git a/src/main/java/io/github/ititus/text/TextUtil.java b/src/main/java/io/github/ititus/text/TextUtil.java index ee7845e..bebf00c 100644 --- a/src/main/java/io/github/ititus/text/TextUtil.java +++ b/src/main/java/io/github/ititus/text/TextUtil.java @@ -5,4 +5,25 @@ public class TextUtil { public static String reverse(String s) { return new StringBuilder(s).reverse().toString(); } + + public static boolean startsWith(CharSequence s, CharSequence prefix) { + if (s instanceof String && prefix instanceof String) { + return ((String) s).startsWith((String) prefix); + } + + int prefixLength = prefix.length(); + if (prefixLength == 0) { + return true; + } else if (s.length() < prefixLength) { + return false; + } + + for (int i = 0; i < prefixLength; i++) { + if (s.charAt(i) != prefix.charAt(i)) { + return false; + } + } + + return true; + } }