Skip to content

Instantly share code, notes, and snippets.

@diamondobama
Last active August 15, 2022 16:49
Show Gist options
  • Save diamondobama/0db1f0c5137129294fdc9254072a77ec to your computer and use it in GitHub Desktop.
Save diamondobama/0db1f0c5137129294fdc9254072a77ec to your computer and use it in GitHub Desktop.
String helper methods to perform various string manipulations in Codename One.
package group.diamonddev.util;
import com.codename1.io.Util;
import com.codename1.l10n.L10NManager;
import com.codename1.util.StringUtil;
import com.codename1.util.regex.RE;
import java.util.*;
/**
* @author Diamond Mubaarak
* @version 1.0
*/
public class StringUtils {
/**
* Convert a given string to title case.
*
* @param string the string value
*
* @return converted string
*/
public static String title(String string) {
if (string == null || string.isEmpty()) return "";
if (string.length() == 1) return string.toUpperCase();
List<String> parts = StringUtil.tokenize(string, " ");
StringBuilder buffer = new StringBuilder(string.length());
for (String part : parts) {
char[] charArray = part.toLowerCase().toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
buffer.append(new String(charArray)).append(" ");
}
return buffer.toString().trim();
}
/**
* Convert a given string to sentence case.
*
* @param string the string value
*
* @return converted string
*/
public static String sentence(String string) {
if (string == null || string.isEmpty()) return "";
if (string.length() == 1) return string.toUpperCase();
char c = string.charAt(0);
String s = "" + c;
String result = string.substring(1).toLowerCase();
return s.toUpperCase() + result;
}
/**
* Convert a given string from camel case to sentence case.
*
* @param text the string value
*
* @return converted string
*/
public static String camelToSentence(String text) {
String string = replaceAll(text, "([A-Z])", " $1");
string = trim(string);
String c = string.substring(0, 1).toUpperCase();
return c + string.substring(1);
}
/**
* Convert a given string from camel case to snake case.
*
* @param string the string value
*
* @return converted string
*/
public static String camelToSnake(String string) {
return camelToSnake(string, '_');
}
/**
* Convert a given string from camel case to snake case.
*
* @param string the string value
* @param delimiter the delimiter character
*
* @return converted string
*/
public static String camelToSnake(String string, char delimiter) {
StringBuilder buffer = new StringBuilder();
char c = string.charAt(0);
buffer.append(Character.toLowerCase(c));
for (int i = 1; i < string.length(); i++) {
char ch = string.charAt(i);
if (Character.isUpperCase(ch)) {
buffer.append(delimiter);
buffer.append(Character.toLowerCase(ch));
} else {
buffer.append(ch);
}
}
return buffer.toString();
}
/**
* Convert a given string to snake case.
*
* @param string the string value
* @param delimiter the delimiter character
*
* @return converted string
*/
public String snake(String string, char delimiter) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
if (Character.isUpperCase(string.charAt(i))) {
if (i > 0) {
buffer.append('_');
}
buffer.append(Character.toLowerCase(string.charAt(i)));
} else {
buffer.append(string.charAt(i));
}
}
return buffer.toString();
}
/**
* Check if a string is in alphanumeric-underscore format
*
* @param text the string value
*
* @return true/false to show whether the string is in the right format
*/
public static boolean isAlphaNumericUnderscore(String text) {
String regex = "^[\\w]+$";
return new RE(regex).match(text);
}
/**
* Helper method to format a decimal while maintaining a fixed length of decimal places by appending zeros when
* necessary.
*
* @param value the double value to be formatted
* @param decimalPlaces the decimal places to apply
*
* @return a formatted decimal string
*/
public static String formatDecimal(double value, int decimalPlaces) {
if (decimalPlaces < 0) return value + "";
L10NManager manager = L10NManager.getInstance();
manager.setLocale("US", "EN"); // To ensure "," is used for thousand delimiter and "." for a decimal separator
String result = manager.format(value, decimalPlaces);
if (!result.contains(".") && decimalPlaces > 0) result += ".";
int dec = result.length() - (result.indexOf(".") + 1);
if (dec <= decimalPlaces) {
int len = result.length() + decimalPlaces - dec;
result = rightPad(result, len, "0");
}
return result;
}
/**
* Splits the provided text into an array, using whitespace as the separator.
*
* @param string the String to split
*
* @return an array of parsed Strings
*/
public static String[] split(String string) {
return split(string, " ");
}
/**
* Splits the provided text into an array, using the specified separator.
*
* @param string the String to split
* @param separator the characters used as the delimiters
*
* @return an array of parsed Strings
*/
public static String[] split(String string, String separator) {
List<String> l = StringUtil.tokenize(string, separator);
return l.toArray(new String[0]);
}
public static String chunk(String text) {
String s = replaceAll(text, "\\D", "");
s = replaceAll(s, "([0-9]{4})", " $0 ");
return rtrim(StringUtil.replaceAll(s.trim(), " ", " "));
}
public static Map<String, List<String>> queryParams(String url) {
try {
Map<String, List<String>> params = new HashMap<>();
List<String> urlParts = StringUtil.tokenize(url, "\\?");
if (urlParts.size() > 1) {
String query = urlParts.get(1);
for (String param : split(query, "&")) {
String[] pair = split(param, "=");
String key = Util.decode(pair[0], "UTF-8", true);
String value = "";
if (pair.length > 1) {
value = Util.decode(pair[1], "UTF-8", true);
}
List<String> values = params.get(key);
if (values == null) {
values = new ArrayList<>();
params.put(key, values);
}
values.add(value);
}
}
return params;
} catch (Exception ex) {
return new HashMap<>();
}
}
/**
* @param strings The array of strings to be joined
*/
public static String sentence(List<String> strings) {
return sentence("&", strings.toArray(new String[0]));
}
/**
* @param joiner The "and" character to use on last item
* @param strings The array of strings to be joined
*/
public static String sentence(String joiner, List<String> strings) {
return sentence(joiner, strings.toArray(new String[0]));
}
/**
* @param joiner The "and" character to use on last item
* @param strings The array of strings to be joined
*/
public static String sentence(String joiner, String... strings) {
String result = "";
if (strings.length > 1) {
result = join(strings, ", ");
result = replaceLast(result, ", ", " " + joiner + " ");
} else if (strings.length == 1) {
result = strings[0];
}
return result;
}
/**
* Replace the last occurrence of a given value in the string.
*
* @param subject subject
* @param search search
* @param replace replace
*
* @return string
*/
public static String replaceLast(String subject, String search, String replace) {
if (search.isEmpty()) return subject;
int lastIndex = subject.lastIndexOf(search);
if (lastIndex < 0) return subject;
String tail = StringUtil.replaceFirst(subject.substring(lastIndex), search, replace);
return subject.substring(0, lastIndex) + tail;
}
/**
* Strip whitespace (or other characters) from the beginning of a string.
*
* @param string the string to trim
*
* @return trimmed string
*/
public static String ltrim(String string) {
return stripStart(string, " \t\r\n\\v\f\b\u007F");
}
/**
* Strip whitespace (or other characters) from the end of a string.
*
* @param string the string to trim
*
* @return trimmed string
*/
public static String rtrim(String string) {
return stripEnd(string, " \t\r\n\\v\f\b\u007F");
}
/**
* Create an acronym from a string.
*
* @param string the string to create acronym from
*
* @return an acronym
*/
public static String acronym(String string, String separator) {
if (string == null || string.isEmpty()) {
return "";
}
StringBuilder builder = new StringBuilder();
List<String> strings = StringUtil.tokenize(string, " ");
for (String s : strings) {
String c = substring(firstNonBlank(s).toUpperCase(), 0, 1);
builder.append(c).append(separator);
}
return rtrim(builder.toString());
}
/**
* Helper method to remove common symbols from a string
*
* @param dirtyString the string to be cleaned
*
* @return a clean string with no bad symbols and space
*/
public static String clean(String dirtyString) {
return clean(dirtyString, "_");
}
/**
* Helper method to remove common symbols from a string
*
* @param dirtyString the string to be cleaned
* @param replacement the replacement for the symbols removed
*
* @return a clean string with no bad symbols and space
*/
public static String clean(String dirtyString, String replacement) {
char[] characterSet = " :&!#*$)(.,`~@+=/\\?'\"][}{|".toCharArray();
return clean(dirtyString, replacement, characterSet);
}
/**
* Helper method to remove common symbols from a string
*
* @param dirtyString the string to be cleaned
* @param characterSet the set of characters to look for
*
* @return a clean string with no bad symbols and space
*/
public static String clean(String dirtyString, char[] characterSet) {
return clean(dirtyString, "_", characterSet);
}
/**
* Helper method to remove common symbols from a string
*
* @param dirtyString the string to be cleaned
* @param replacement the replacement for the symbols removed
* @param characterSet the set of characters to look for
*
* @return a clean string with no bad symbols and space
*/
public static String clean(String dirtyString, String replacement, char[] characterSet) {
String result = dirtyString;
for (char c : characterSet) {
char[] value = {c};
result = StringUtil.replaceAll(result, new String(value), replacement);
}
return result;
}
@SafeVarargs
public static <T extends CharSequence> T firstNonBlank(T... values) {
if (values != null) {
int var2 = values.length;
for (int var3 = 0; var3 < var2; ++var3) {
T val = (T) ((CharSequence[]) values)[var3];
if (isNotBlank(val)) {
return val;
}
}
}
return null;
}
@SafeVarargs
public static <T extends CharSequence> T firstNonEmpty(T... values) {
if (values != null) {
int var2 = values.length;
for (int var3 = 0; var3 < var2; ++var3) {
T val = (T) ((CharSequence[]) values)[var3];
if (isNotEmpty(val)) {
return val;
}
}
}
return null;
}
public static String center(String str, int size) {
return center(str, size, ' ');
}
public static String center(String str, int size, char padChar) {
if (str != null && size > 0) {
int strLen = str.length();
int pads = size - strLen;
if (pads > 0) {
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
}
}
return str;
}
public static String center(String str, int size, String padStr) {
if (str != null && size > 0) {
if (isEmpty(padStr)) {
padStr = " ";
}
int strLen = str.length();
int pads = size - strLen;
if (pads > 0) {
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
}
}
return str;
}
public static String chomp(String str) {
if (isEmpty(str)) {
return str;
} else if (str.length() == 1) {
char ch = str.charAt(0);
return ch != '\r' && ch != '\n' ? str : "";
} else {
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == '\n') {
if (str.charAt(lastIdx - 1) == '\r') {
--lastIdx;
}
} else if (last != '\r') {
++lastIdx;
}
return str.substring(0, lastIdx);
}
}
/**
* @deprecated
*/
@Deprecated
public static String chomp(String str, String separator) {
return removeEnd(str, separator);
}
public static String chop(String str) {
if (str == null) {
return null;
} else {
int strLen = str.length();
if (strLen < 2) {
return "";
} else {
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
return last == '\n' && ret.charAt(lastIdx - 1) == '\r' ? ret.substring(0, lastIdx - 1) : ret;
}
}
}
public static int compare(String str1, String str2) {
return compare(str1, str2, true);
}
public static int compare(String str1, String str2, boolean nullIsLess) {
if (Objects.equals(str1, str2)) {
return 0;
} else if (str1 == null) {
return nullIsLess ? -1 : 1;
} else if (str2 == null) {
return nullIsLess ? 1 : -1;
} else {
return str1.compareTo(str2);
}
}
public static int compareIgnoreCase(String str1, String str2) {
return compareIgnoreCase(str1, str2, true);
}
public static int compareIgnoreCase(String str1, String str2, boolean nullIsLess) {
if (Objects.equals(str1, str2)) {
return 0;
} else if (str1 == null) {
return nullIsLess ? -1 : 1;
} else if (str2 == null) {
return nullIsLess ? 1 : -1;
} else {
return str1.compareToIgnoreCase(str2);
}
}
public static boolean containsNone(CharSequence cs, char... searchChars) {
if (cs != null && searchChars != null) {
int csLen = cs.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = 0; i < csLen; ++i) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLen; ++j) {
if (searchChars[j] == ch) {
if (!Character.isHighSurrogate(ch)) {
return false;
}
if (j == searchLast) {
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
}
}
}
}
return true;
}
public static boolean containsNone(CharSequence cs, String invalidChars) {
return cs == null || invalidChars == null || containsNone(cs, invalidChars.toCharArray());
}
public static boolean containsWhitespace(CharSequence seq) {
if (!isEmpty(seq)) {
int strLen = seq.length();
for (int i = 0; i < strLen; ++i) {
if (Character.isWhitespace(seq.charAt(i))) {
return true;
}
}
}
return false;
}
private static void convertRemainingAccentCharacters(StringBuilder decomposed) {
for (int i = 0; i < decomposed.length(); ++i) {
if (decomposed.charAt(i) == 321) {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'L');
} else if (decomposed.charAt(i) == 322) {
decomposed.deleteCharAt(i);
decomposed.insert(i, 'l');
}
}
}
public static int countMatches(CharSequence str, char ch) {
if (isEmpty(str)) {
return 0;
} else {
int count = 0;
for (int i = 0; i < str.length(); ++i) {
if (ch == str.charAt(i)) {
++count;
}
}
return count;
}
}
public static <T extends CharSequence> T defaultIfBlank(T str, T defaultStr) {
return isBlank(str) ? defaultStr : str;
}
public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr) {
return isEmpty(str) ? defaultStr : str;
}
public static String defaultString(String str) {
return defaultString(str, "");
}
public static String defaultString(String str, String defaultStr) {
return str == null ? defaultStr : str;
}
public static String deleteWhitespace(String str) {
if (isEmpty(str)) {
return str;
} else {
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
} else {
return new String(chs, 0, count);
}
}
}
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
} else if (str2 == null) {
return str1;
} else {
int at = indexOfDifference(str1, str2);
return at == -1 ? "" : str2.substring(at);
}
}
public static boolean equals(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return true;
} else if (cs1 != null && cs2 != null) {
if (cs1.length() != cs2.length()) {
return false;
} else if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
} else {
int length = cs1.length();
for (int i = 0; i < length; ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
return false;
}
}
return true;
}
} else {
return false;
}
}
public static String getDigits(String str) {
if (isEmpty(str)) {
return str;
} else {
int sz = str.length();
StringBuilder strDigits = new StringBuilder(sz);
for (int i = 0; i < sz; ++i) {
char tempChar = str.charAt(i);
if (Character.isDigit(tempChar)) {
strDigits.append(tempChar);
}
}
return strDigits.toString();
}
}
public static int indexOfDifference(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return -1;
} else if (cs1 != null && cs2 != null) {
int i;
for (i = 0; i < cs1.length() && i < cs2.length() && cs1.charAt(i) == cs2.charAt(i); ++i) {
System.out.println();
}
return i >= cs2.length() && i >= cs1.length() ? -1 : i;
} else {
return 0;
}
}
public static boolean isAllLowerCase(CharSequence cs) {
if (isEmpty(cs)) {
return false;
} else {
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isLowerCase(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static boolean isAllUpperCase(CharSequence cs) {
if (isEmpty(cs)) {
return false;
} else {
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isUpperCase(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static boolean isBlank(CharSequence cs) {
int strLen = length(cs);
if (strLen != 0) {
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
}
return true;
}
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isMixedCase(CharSequence cs) {
if (!isEmpty(cs) && cs.length() != 1) {
boolean containsUppercase = false;
boolean containsLowercase = false;
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (containsUppercase && containsLowercase) {
return true;
}
if (Character.isUpperCase(cs.charAt(i))) {
containsUppercase = true;
} else if (Character.isLowerCase(cs.charAt(i))) {
containsLowercase = true;
}
}
return containsUppercase && containsLowercase;
} else {
return false;
}
}
public static boolean isNotBlank(CharSequence cs) {
return !isBlank(cs);
}
public static boolean isNotEmpty(CharSequence cs) {
return !isEmpty(cs);
}
public static boolean isNumeric(CharSequence cs) {
if (isEmpty(cs)) {
return false;
} else {
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static boolean isNumericSpace(CharSequence cs) {
if (cs == null) {
return false;
} else {
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
}
public static boolean isWhitespace(CharSequence cs) {
if (cs == null) {
return false;
} else {
int sz = cs.length();
for (int i = 0; i < sz; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static String join(byte[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(byte[] array, char separator, int startIndex, int endIndex) {
return joinObj(new byte[][]{array}, separator, startIndex, endIndex);
}
public static String join(char[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(char[] array, char separator, int startIndex, int endIndex) {
return joinObj(new char[][]{array}, separator, startIndex, endIndex);
}
public static String join(double[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(double[] array, char separator, int startIndex, int endIndex) {
return joinObj(new double[][]{array}, separator, startIndex, endIndex);
}
public static String join(float[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(float[] array, char separator, int startIndex, int endIndex) {
return joinObj(new float[][]{array}, separator, startIndex, endIndex);
}
public static String join(int[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(int[] array, char separator, int startIndex, int endIndex) {
return joinObj(new int[][]{array}, separator, startIndex, endIndex);
}
public static String join(Iterable<?> iterable, char separator) {
return iterable == null ? null : join(iterable.iterator(), separator);
}
public static String join(Iterable<?> iterable, String separator) {
return iterable == null ? null : join(iterable.iterator(), separator);
}
public static String join(Iterator<?> iterator, char separator) {
if (iterator == null) {
return null;
} else if (!iterator.hasNext()) {
return "";
} else {
Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, "");
} else {
StringBuilder buf = new StringBuilder(256);
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
}
}
public static String join(Iterator<?> iterator, String separator) {
if (iterator == null) {
return null;
} else if (!iterator.hasNext()) {
return "";
} else {
Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, "");
} else {
StringBuilder buf = new StringBuilder(256);
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
}
}
public static String join(List<?> list, char separator, int startIndex, int endIndex) {
if (list == null) {
return null;
} else {
int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return "";
} else {
List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
}
}
public static String join(List<?> list, String separator, int startIndex, int endIndex) {
if (list == null) {
return null;
} else {
int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return "";
} else {
List<?> subList = list.subList(startIndex, endIndex);
return join(subList.iterator(), separator);
}
}
}
public static String join(long[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(long[] array, char separator, int startIndex, int endIndex) {
return joinObj(new long[][]{array}, separator, startIndex, endIndex);
}
public static String join(Object[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(Object[] array, char separator, int startIndex, int endIndex) {
return joinObj(array, separator, startIndex, endIndex);
}
public static String joinObj(Object[] array, char separator, int startIndex, int endIndex) {
if (array == null) {
return null;
} else {
return joiner(array, separator + "", startIndex, endIndex);
}
}
public static String join(Object[] array, String separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(Object[] array, String separator, int startIndex, int endIndex) {
if (array == null) {
return null;
} else {
if (separator == null) {
separator = "";
}
return joiner(array, separator, startIndex, endIndex);
}
}
private static String joiner(Object[] array, String separator, int startIndex, int endIndex) {
int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return "";
} else {
StringBuilder buf = newStringBuilder(noOfItems);
if (array[startIndex] != null) {
buf.append(array[startIndex]);
}
for (int i = startIndex + 1; i < endIndex; ++i) {
buf.append(separator);
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
public static String join(short[] array, char separator) {
return array == null ? null : join(array, separator, 0, array.length);
}
public static String join(short[] array, char separator, int startIndex, int endIndex) {
return joinObj(new short[][]{array}, separator, startIndex, endIndex);
}
@SafeVarargs
public static <T> String join(T... elements) {
return join(elements, null);
}
public static String joinWith(String separator, Object... objects) {
if (objects == null) {
throw new IllegalArgumentException("Object varargs must not be null");
} else {
String sanitizedSeparator = defaultString(separator);
StringBuilder result = new StringBuilder();
Iterator iterator = Arrays.asList(objects).iterator();
while (iterator.hasNext()) {
String value = Objects.toString(iterator.next(), "");
result.append(value);
if (iterator.hasNext()) {
result.append(sanitizedSeparator);
}
}
return result.toString();
}
}
public static String left(String str, int len) {
if (str == null) {
return null;
} else if (len < 0) {
return "";
} else {
return str.length() <= len ? str : str.substring(0, len);
}
}
public static String leftPad(String str, int size) {
return leftPad(str, size, ' ');
}
public static String leftPad(String str, int size, char padChar) {
if (str == null) {
return null;
} else {
int pads = size - str.length();
if (pads <= 0) {
return str;
} else {
return pads > 8192 ? leftPad(str, size, String.valueOf(padChar)) : repeat(padChar, pads).concat(str);
}
}
}
public static String leftPad(String str, int size, String padStr) {
if (str == null) {
return null;
} else {
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
} else if (padLen == 1 && pads <= 8192) {
return leftPad(str, size, padStr.charAt(0));
} else if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; ++i) {
padding[i] = padChars[i % padLen];
}
return (new String(padding)).concat(str);
}
}
}
public static int length(CharSequence cs) {
return cs == null ? 0 : cs.length();
}
public static String lowerCase(String str) {
return str == null ? null : str.toLowerCase();
}
private static int[] matches(CharSequence first, CharSequence second) {
CharSequence max;
CharSequence min;
if (first.length() > second.length()) {
max = first;
min = second;
} else {
max = second;
min = first;
}
int range = Math.max(max.length() / 2 - 1, 0);
int[] matchIndexes = new int[min.length()];
Arrays.fill(matchIndexes, -1);
boolean[] matchFlags = new boolean[max.length()];
int matches = 0;
int transpositions;
int prefix;
for (int mi = 0; mi < min.length(); ++mi) {
char c1 = min.charAt(mi);
transpositions = Math.max(mi - range, 0);
for (prefix = Math.min(mi + range + 1, max.length()); transpositions < prefix; ++transpositions) {
if (!matchFlags[transpositions] && c1 == max.charAt(transpositions)) {
matchIndexes[mi] = transpositions;
matchFlags[transpositions] = true;
++matches;
break;
}
}
}
char[] ms1 = new char[matches];
char[] ms2 = new char[matches];
transpositions = 0;
for (prefix = 0; transpositions < min.length(); ++transpositions) {
if (matchIndexes[transpositions] != -1) {
ms1[prefix] = min.charAt(transpositions);
++prefix;
}
}
transpositions = 0;
for (prefix = 0; transpositions < max.length(); ++transpositions) {
if (matchFlags[transpositions]) {
ms2[prefix] = max.charAt(transpositions);
++prefix;
}
}
transpositions = 0;
for (prefix = 0; prefix < ms1.length; ++prefix) {
if (ms1[prefix] != ms2[prefix]) {
++transpositions;
}
}
prefix = 0;
for (int mi = 0; mi < min.length() && first.charAt(mi) == second.charAt(mi); ++mi) {
++prefix;
}
return new int[]{matches, transpositions / 2, prefix, max.length()};
}
public static String mid(String str, int pos, int len) {
if (str == null) {
return null;
} else if (len >= 0 && pos <= str.length()) {
if (pos < 0) {
pos = 0;
}
return str.length() <= pos + len ? str.substring(pos) : str.substring(pos, pos + len);
} else {
return "";
}
}
private static StringBuilder newStringBuilder(int noOfItems) {
return new StringBuilder(noOfItems * 16);
}
public static String normalizeSpace(String str) {
if (isEmpty(str)) {
return str;
} else {
int size = str.length();
char[] newChars = new char[size];
int count = 0;
int whitespacesCount = 0;
boolean startWhitespaces = true;
for (int i = 0; i < size; ++i) {
char actualChar = str.charAt(i);
boolean isWhitespace = Character.isWhitespace(actualChar);
if (isWhitespace) {
if (whitespacesCount == 0 && !startWhitespaces) {
newChars[count++] = " ".charAt(0);
}
++whitespacesCount;
} else {
startWhitespaces = false;
newChars[count++] = actualChar == 160 ? 32 : actualChar;
whitespacesCount = 0;
}
}
if (startWhitespaces) {
return "";
} else {
return (new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0))).trim();
}
}
}
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
} else {
if (overlay == null) {
overlay = "";
}
int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
int temp = start;
start = end;
end = temp;
}
return str.substring(0, start) + overlay + str.substring(end);
}
}
public static String remove(String str, char remove) {
if (!isEmpty(str) && str.indexOf(remove) != -1) {
char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; ++i) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
} else {
return str;
}
}
public static String removeEnd(String str, String remove) {
if (!isEmpty(str) && !isEmpty(remove)) {
return str.endsWith(remove) ? str.substring(0, str.length() - remove.length()) : str;
} else {
return str;
}
}
public static String removeStart(String str, String remove) {
if (!isEmpty(str) && !isEmpty(remove)) {
return str.startsWith(remove) ? str.substring(remove.length()) : str;
} else {
return str;
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
} else {
char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; --i) {
buf[i] = ch;
}
return new String(buf);
}
}
public static String repeat(String str, int repeat) {
if (str == null) {
return null;
} else if (repeat <= 0) {
return "";
} else {
int inputLength = str.length();
if (repeat != 1 && inputLength != 0) {
if (inputLength == 1 && repeat <= 8192) {
return repeat(str.charAt(0), repeat);
} else {
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1:
return repeat(str.charAt(0), repeat);
case 2:
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; --i) {
output2[i] = ch0;
output2[i + 1] = ch1;
--i;
}
return new String(output2);
default:
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; ++i) {
buf.append(str);
}
return buf.toString();
}
}
} else {
return str;
}
}
}
public static String repeat(String str, String separator, int repeat) {
if (str != null && separator != null) {
String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
} else {
return repeat(str, repeat);
}
}
public static String replace(String str, String needle, String replacement) {
return replaceAll(str, needle, replacement);
}
public static String replaceAll(String str, String regex, String replacement) {
RE r = new RE(regex);
return r.subst(str, replacement, 2);
}
public static String replaceChars(String str, char searchChar, char replaceChar) {
return str == null ? null : str.replace(searchChar, replaceChar);
}
public static String replaceChars(String str, String searchChars, String replaceChars) {
if (!isEmpty(str) && !isEmpty(searchChars)) {
if (replaceChars == null) {
replaceChars = "";
}
boolean modified = false;
int replaceCharsLength = replaceChars.length();
int strLength = str.length();
StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; ++i) {
char ch = str.charAt(i);
int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
} else {
return str;
}
} else {
return str;
}
}
public static String reverse(String str) {
return str == null ? null : (new StringBuilder(str)).reverse().toString();
}
public static String right(String str, int len) {
if (str == null) {
return null;
} else if (len < 0) {
return "";
} else {
return str.length() <= len ? str : str.substring(str.length() - len);
}
}
public static String rightPad(String str, int size) {
return rightPad(str, size, ' ');
}
public static String rightPad(String str, int size, char padChar) {
if (str == null) {
return null;
} else {
int pads = size - str.length();
if (pads <= 0) {
return str;
} else {
return pads > 8192 ? rightPad(str, size, String.valueOf(padChar)) : str.concat(repeat(padChar, pads));
}
}
}
public static String rightPad(String str, int size, String padStr) {
if (str == null) {
return null;
} else {
if (isEmpty(padStr)) {
padStr = " ";
}
int padLen = padStr.length();
int strLen = str.length();
int pads = size - strLen;
if (pads <= 0) {
return str;
} else if (padLen == 1 && pads <= 8192) {
return rightPad(str, size, padStr.charAt(0));
} else if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
char[] padding = new char[pads];
char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; ++i) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
}
public static String rotate(String str, int shift) {
if (str == null) {
return null;
} else {
int strLen = str.length();
if (shift != 0 && strLen != 0 && shift % strLen != 0) {
StringBuilder builder = new StringBuilder(strLen);
int offset = -(shift % strLen);
builder.append(substring(str, offset));
builder.append(substring(str, 0, offset));
return builder.toString();
} else {
return str;
}
}
}
public static String strip(String str) {
return strip(str, null);
}
public static String strip(String str, String stripChars) {
if (isEmpty(str)) {
return str;
} else {
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
}
public static String stripEnd(String str, String stripChars) {
int end = length(str);
if (end == 0) {
return str;
} else {
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
--end;
}
} else {
if (stripChars.isEmpty()) {
return str;
}
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != -1) {
--end;
}
}
return str.substring(0, end);
}
}
public static String stripStart(String str, String stripChars) {
int strLen = length(str);
if (strLen == 0) {
return str;
} else {
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
++start;
}
} else {
if (stripChars.isEmpty()) {
return str;
}
while (start != strLen && stripChars.indexOf(str.charAt(start)) != -1) {
++start;
}
}
return str.substring(start);
}
}
public static String stripToEmpty(String str) {
return str == null ? "" : strip(str, null);
}
public static String stripToNull(String str) {
if (str == null) {
return null;
} else {
str = strip(str, null);
return str.isEmpty() ? null : str;
}
}
public static String substring(String str, int start) {
if (str == null) {
return null;
} else {
if (start < 0) {
start += str.length();
}
if (start < 0) {
start = 0;
}
return start > str.length() ? "" : str.substring(start);
}
}
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
} else {
if (end < 0) {
end += str.length();
}
if (start < 0) {
start += str.length();
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return "";
} else {
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
}
}
public static String substringAfter(String str, int separator) {
if (isEmpty(str)) {
return str;
} else {
int pos = str.indexOf(separator);
return pos == -1 ? "" : str.substring(pos + 1);
}
}
public static String substringAfter(String str, String separator) {
if (isEmpty(str)) {
return str;
} else if (separator == null) {
return "";
} else {
int pos = str.indexOf(separator);
return pos == -1 ? "" : str.substring(pos + separator.length());
}
}
public static String substringAfterLast(String str, int separator) {
if (isEmpty(str)) {
return str;
} else {
int pos = str.lastIndexOf(separator);
return pos != -1 && pos != str.length() - 1 ? str.substring(pos + 1) : "";
}
}
public static String substringAfterLast(String str, String separator) {
if (isEmpty(str)) {
return str;
} else if (isEmpty(separator)) {
return "";
} else {
int pos = str.lastIndexOf(separator);
return pos != -1 && pos != str.length() - separator.length() ? str.substring(pos + separator.length()) : "";
}
}
public static String substringBefore(String str, String separator) {
if (!isEmpty(str) && separator != null) {
if (separator.isEmpty()) {
return "";
} else {
int pos = str.indexOf(separator);
return pos == -1 ? str : str.substring(0, pos);
}
} else {
return str;
}
}
public static String substringBeforeLast(String str, String separator) {
if (!isEmpty(str) && !isEmpty(separator)) {
int pos = str.lastIndexOf(separator);
return pos == -1 ? str : str.substring(0, pos);
} else {
return str;
}
}
public static String trim(String str) {
return str == null ? null : str.trim();
}
public static String trimToEmpty(String str) {
return str == null ? "" : str.trim();
}
public static String trimToNull(String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
public static String truncate(String str, int maxWidth) {
return truncate(str, 0, maxWidth);
}
public static String truncate(String str, int offset, int maxWidth) {
if (offset < 0) {
throw new IllegalArgumentException("offset cannot be negative");
} else if (maxWidth < 0) {
throw new IllegalArgumentException("maxWith cannot be negative");
} else if (str == null) {
return null;
} else if (offset > str.length()) {
return "";
} else if (str.length() > maxWidth) {
int ix = Math.min(offset + maxWidth, str.length());
return str.substring(offset, ix);
} else {
return str.substring(offset);
}
}
public static String upperCase(String str) {
return str == null ? null : str.toUpperCase();
}
public static String valueOf(char[] value) {
return value == null ? null : String.valueOf(value);
}
public static String wrap(String str, char wrapWith) {
return !isEmpty(str) && wrapWith != 0 ? wrapWith + str + wrapWith : str;
}
public static String wrap(String str, String wrapWith) {
return !isEmpty(str) && !isEmpty(wrapWith) ? wrapWith.concat(str).concat(wrapWith) : str;
}
public static String wrapIfMissing(String str, char wrapWith) {
if (!isEmpty(str) && wrapWith != 0) {
boolean wrapStart = str.charAt(0) != wrapWith;
boolean wrapEnd = str.charAt(str.length() - 1) != wrapWith;
if (!wrapStart && !wrapEnd) {
return str;
} else {
StringBuilder builder = new StringBuilder(str.length() + 2);
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
} else {
return str;
}
}
public static String wrapIfMissing(String str, String wrapWith) {
if (!isEmpty(str) && !isEmpty(wrapWith)) {
boolean wrapStart = !str.startsWith(wrapWith);
boolean wrapEnd = !str.endsWith(wrapWith);
if (!wrapStart && !wrapEnd) {
return str;
} else {
StringBuilder builder = new StringBuilder(str.length() + wrapWith.length() + wrapWith.length());
if (wrapStart) {
builder.append(wrapWith);
}
builder.append(str);
if (wrapEnd) {
builder.append(wrapWith);
}
return builder.toString();
}
} else {
return str;
}
}
}
@diamondobama
Copy link
Author

@MoKamal I added more methods you may find useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment