Add countOccurrences and getSeparator methods

This commit is contained in:
JeremyStar™ 2024-06-29 04:25:31 +02:00
parent e0db4be65a
commit 5011fb8ae9
Signed by: JeremyStarTM
GPG key ID: E366BAEF67E4704D
2 changed files with 50 additions and 0 deletions

View file

@ -24,6 +24,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@ -114,4 +115,52 @@ public final class Miscellaneous {
new ThrowableCatchEvent().callEvent(throwable, identifier);
}
}
/**
* Counts the occurrences of a substring inside of a string.
*
* @param string string to search
* @param substring substring to search for
* @return occurrences
*/
public static long countOccurrences(@NotNull String string, @NotNull String substring) {
return (string.length() - string.replace(substring, "").length()) / substring.length();
}
/**
* Returns the correct separator to use when splitting a string.
*
* @param string string to split
* @param separators separators to check
* @param requiredOccurrences exact amount of occurrences for a separator to be deemed valid
* @return separator to use or {@code null}
* @since 1-alpha1
*/
@Nullable
public static String getSeparator(@NotNull String string, String[] separators, int requiredOccurrences) {
if (string.isBlank() || separators.length == 0 || requiredOccurrences == 0)
return null;
for (String separator : separators)
if (countOccurrences(string, separator) == requiredOccurrences)
return separator;
return null;
}
/**
* Returns the correct separator to use when splitting a string.
*
* @param string string to split
* @param separators separators to check
* @param minimumOccurrences minimum amount of occurrences for a separator to be deemed valid
* @return separator to use or {@code null}
* @since 1-alpha1
*/
@Nullable
public static String getSeparator(@NotNull String string, List<String> separators, Integer minimumOccurrences) {
for (String separator : separators)
if (countOccurrences(string, separator) >= minimumOccurrences)
return separator;
return null;
}
}

View file

@ -45,6 +45,7 @@ class EngineConfigurationTest {
* The unit logger for this instance.
*/
private static final UnitLogger logger = new UnitLogger(EngineConfigurationTest.class);
/**
* The property group for the base engine.
*/