com.xlrit.gears.base.util.StringUtils Maven / Gradle / Ivy
package com.xlrit.gears.base.util;
import java.util.IllformedLocaleException;
import java.util.Locale;
import java.util.Objects;
public class StringUtils {
public static String capitalize(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static String uncapitalize(String s) {
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
/** Converts camel case to snake case. */
public static String toSnakeCase(String str) {
return str.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase();
}
/**
* Surrounds a string with single quotes.
*/
public static String quote(String s) {
return "'" + s + "'";
}
/**
* Removes single quotes surrounding a string.
*/
public static String unquote(String text) {
Objects.requireNonNull(text);
assert(text.length() >= 2);
assert(text.charAt(0) == '\'');
assert(text.charAt(text.length() - 1) == '\'');
return text.substring(1, text.length() - 1);
}
public static boolean nonEmpty(String s) {
return s != null && !s.isBlank();
}
public static String trim(String s) {
return s == null ? null : s.trim();
}
/** Convert a language tag string to Locale like Locale.forLanguageTag, but check the tags syntax first. */
public static Locale toLocale(String languageTag) {
// First parse the language tag and report parsing errors. This does not happen with Locale.forLanguageTag.
try {
return new Locale.Builder()
.setLanguageTag(languageTag)
.build();
}
catch (IllformedLocaleException e) {
throw new IllegalArgumentException(String.format("Invalid language: '%s'", languageTag) + " \n" + e.getMessage());
}
}
}