Skip to content

Commit

Permalink
MCStrings: Added indexOf methods
Browse files Browse the repository at this point in the history
  • Loading branch information
xDec0de committed Sep 3, 2024
1 parent 2bdda54 commit 9dd229d
Showing 1 changed file with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ public static String asString(@NotNull Iterable<CharSequence> iterable, @Nullabl
@NotNull
public static String asString(@NotNull Iterable<CharSequence> iterable, @Nullable CharSequence separator) {
return asString(iterable, separator, MCStrings::hasContent);
}



Expand All @@ -250,6 +251,50 @@ public static String asString(@NotNull Iterable<CharSequence> iterable, @Nullabl



/*
* CharSequence utility
*/

/**
* Gets the index of {@code toFind} on {@code seq}, starting to search at {@code beginIndex}.
* In other words, this method will search for the first occurrence of {@code toFind} inside of
* {@code seq} starting at {@code beginIndex}, then return the index at which {@code toFind} <b>starts</b>.
*
* @param seq the {@link CharSequence} to search on.
* @param toFind the {@link CharSequence} to find inside {@code seq}.
* @param beginIndex the index of {@code seq} to start searching from, negative values
* will make this method <b>always</b> return {@code -1}.
*
* @return the index of {@code seq} at which {@code toFind} is located, if found. {@code -1} if
* {@code toFind} could not be found inside {@code seq}. Another instance where this method returns
* {@code -1} is when {@code beginIndex} is negative or higher than the {@link CharSequence#length()
* length} of {@code seq}. If {@code toFind}'s {@link CharSequence#length() length} is {@code 0},
* then {@code 0} will be returned as an empty string is considered to always match.
*
* @throws NullPointerException if {@code seq} or {@code toFind} are {@code null}.
*
* @since MCUtils 1.0.0
*/
public static int indexOf(@NotNull CharSequence seq, @NotNull CharSequence toFind, int beginIndex) {
final int seqLen = seq.length();
final int toFindLen = toFind.length();
if (beginIndex < 0)
return -1;
if (toFindLen == 0)
return 0;
for (int i = beginIndex; i < seqLen; i++) {
for (int j = 0; j < toFindLen && i + j < seqLen; j++) {
if (seq.charAt(i + j) != toFind.charAt(j))
break;
if (toFindLen == j + 1)
return i;
}
}
return -1;
}

public static int indexOf(@NotNull CharSequence seq, @NotNull CharSequence toFind) {
return indexOf(seq, toFind, 0);
}

/*
Expand Down

0 comments on commit 9dd229d

Please sign in to comment.