Bat/src/main/java/cc/fascinated/bat/common/StringUtils.java
Liam 217b284f14
Some checks failed
Deploy to Dokku / docker (ubuntu-latest) (push) Has been cancelled
move lookup to a sub command and add mem usage to the bot stats command
2024-07-07 01:34:27 +01:00

55 lines
1.6 KiB
Java

package cc.fascinated.bat.common;
import lombok.experimental.UtilityClass;
/**
* @author Fascinated (fascinated7)
*/
@UtilityClass
public class StringUtils {
/**
* Generates a random string
*
* @param length the length of the string
* @return the random string
*/
public static String randomString(int length) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
stringBuilder.append((char) (Math.random() * 26 + 'a'));
}
return stringBuilder.toString();
}
/**
* Escapes meta characters in a string
*
* @param inputString the input string
* @return the string with escaped meta characters
*/
public static String escapeMetaCharacters(String inputString){
final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};
for (String metaCharacter : metaCharacters) {
if (inputString.contains(metaCharacter)) {
inputString = inputString.replace(metaCharacter, "\\" + metaCharacter);
}
}
return inputString;
}
/**
* Formats bytes into a human-readable format
*
* @param bytes the bytes
* @return the formatted bytes
*/
public static String formatBytes(long bytes) {
int unit = 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
char pre = "KMGTPE".charAt(exp-1);
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
}