Skip to content

Commit

Permalink
add some helper methods for text
Browse files Browse the repository at this point in the history
  • Loading branch information
iTitus committed Oct 23, 2021
1 parent 659a8ca commit 14a2ca8
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/main/java/io/github/ititus/text/SubCharSequence.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
21 changes: 21 additions & 0 deletions src/main/java/io/github/ititus/text/TextUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

0 comments on commit 14a2ca8

Please sign in to comment.