All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xdev.util.StringUtils Maven / Gradle / Ivy

/*
 * XDEV Application Framework - XDEV Application Framework
 * Copyright © 2003 XDEV Software (https://xdev.software)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see .
 */
package xdev.util;


import java.util.Collection;
import java.util.Map;
import java.util.StringTokenizer;

import xdev.lang.LibraryMember;
import xdev.lang.NotNull;


/**
 * 

* The StringUtils class provides utility methods for * {@link String} handling. *

* * @since 2.0 * * @author XDEV Software */ @LibraryMember public final class StringUtils { /** * newline constant used in StringUtils. */ public final static String NEWLINE = "\n"; /** * line feed constant used in StringUtils. */ public final static String LINEFEED = "\r"; /** * tab constant used in StringUtils. */ public final static String TAB = "\t"; /** *

* StringUtils instances can not be instantiated. The class * should be used as utility class: * StringUtils.getUnicodeNr("bar");. *

*/ private StringUtils() { } /** * Gets the character at index as new String. * *

* Examples:

* *
	 * StringUtils.charAt("XDEV", 0) returns "X"
	 * StringUtils.charAt("Bar", 2) returns "r"
	 * StringUtils.charAt("Hello XDEV3", 6) returns "X"
	 * 
* *
*

* * @param str * the String to get the character from. * @param index * the position of the character. 0 <= index < * length of str. The first character has * index 0. * @return the character at the specified index of str. The * first char value is at index 0. * @throws NullPointerException * if str is null * @throws IndexOutOfBoundsException * if the index argument is negative or not less * than the length of str. * * */ @NotNull public static String charAt(@NotNull String str, int index) throws NullPointerException, IndexOutOfBoundsException { return String.valueOf(str.charAt(index)); } /** * Returns true if and only if {@link String} str * contains the specified {@link String} search. This method is * case sensitive. * *

* Examples:

* *
	 * StringUtils.contains("Hello XDEV3", "beta")  returns false
	 * StringUtils.contains("Hello XDEV3", "Xdev3") returns false
	 * StringUtils.contains("Hello XDEV3", "XDEV3") returns true
	 * 
* *
*

* * * @param str * the {@link String} to search in * @param search * the {@link String} to search for * @return true if {@link String} str contains * search, false otherwise * @throws NullPointerException * if str is null * @throws NullPointerException * if search is null * */ public static boolean contains(@NotNull String str, @NotNull String search) throws NullPointerException { return str.indexOf(search) >= 0; } /** * Returns a new string that is a substring of str. The * substring begins with the character at the specified index * start and contains the following number of characters * specified by length. *

* Examples:

* *
	 * StringUtils.substr("New York",4,4) returns "York"
	 * StringUtils.substr("New York",0,3) returns "New"
	 * 
* *
*

* * @param str * the {@link String} to operate on * @param start * the beginning index, inclusive. * @param length * the length of the substring * @return the specified substring. * * @throws NullPointerException * if str is null * * @throws IndexOutOfBoundsException * if start is negative or greater than the length * of str. If length is negative or * greater than the length of str - * start. */ @NotNull public static String substr(@NotNull String str, int start, int length) throws NullPointerException, IndexOutOfBoundsException { return str.substring(start,start + length); } /** * Replaces each substring of the given {@link String} source * that matches the given {@link String} search with the given * {@link String} replacement. * *

* Hint: The {@link String} source remains * unchanged. All operations take place on a newly created String that is * returned by this method. *

* *

* Examples:

* *
	 *  StringUtils.replaceAll("This is a String","is","at") returns "That at a String"
	 *  StringUtils.replaceAll("In Betatest","In","For")     returns "For Betatest"
	 * 
* *
*

* * * @param source * {@link String} to search in * @param search * {@link String} to search for * @param replacement * {@link String} to replace the {@link String} * search with * @return the result of the replace operation * * @throws NullPointerException * if source, search or * replacement are null. * */ @NotNull public static String replaceAll(@NotNull String source, @NotNull String search, @NotNull String replacement) throws NullPointerException { return source.replace(search,replacement); // String _source = new String(source); // // if(search.length() > 0) // { // int searchLen = search.length(); // int replacementLen = replacement.length(); // int si = _source.indexOf(search); // // while(si >= 0) // { // int sourceLen = _source.length(); // // char[] newChars = new char[sourceLen - searchLen + replacementLen]; // // if(si > 0) // { // _source.getChars(0,si,newChars,0); // } // // if(replacementLen > 0) // { // replacement.getChars(0,replacementLen,newChars,si); // } // // int si2 = si + searchLen; // if(si2 < sourceLen) // { // _source.getChars(si2,sourceLen,newChars,si + replacementLen); // } // // _source = new String(newChars); // si = _source.indexOf(search,si + replacementLen); // } // } // // return _source; } /** * Splits a the {@link String} str at every separator * {@link String} separator. * *

* Examples:

* *
	 * XdevList<String> expected = new XdevList<String>();
	 * expected.add("Hello");
	 * expected.add("XDEV3");
	 * XdevList<String> actual = StringUtils.explode("Hello,XDEV3",",");
	 * Assert.assertEquals(expected,actual);
	 * 
	 * 
* *
*

*

* This method is a alias for * StringUtils.explode(str, separator, false) *

* * @param str * the {@link String} to be split * @param separator * the separator * * @return {@link XdevList} containing all parts of the given {@link String} * str split at every separator {@link String} * separator. * @see #explode(String, String, boolean) */ @NotNull public static XdevList explode(@NotNull String str, @NotNull String separator) { return explode(str,separator,false); } /** * Splits a the {@link String} str at every separator * {@link String} separator. * *

* Examples:

* *
	 * StringUtils.explode("XDEV IDE based on java", " ", true)  returns a list with 9 elements 
	 * StringUtils.explode("XDEV IDE based on java", " ", false) returns a list with 5 elements
	 *  XdevList expected = new XdevList();
	 * expected.add("Hello");
	 * expected.add("world");
	 * expected.add("and");
	 * expected.add("space");
	 * XdevList actual = StringUtils.explode("Hello,world,and,space", ",",false);
	 * 
* *
*

* * * * @param str * the {@link String} to be split * @param separator * the separator * @param returnDelimiters * if true the separator is returned as independent * element in the list; otherwise it is not. * @return {@link XdevList} containing all parts of the given {@link String} * str split at every separator {@link String} * separator. * * @throws NullPointerException * if eighter str or separator is * null * @see #explode(String, String) * @see #concat(String, Collection) * @see #concat(String, Object...) */ @NotNull public static XdevList explode(@NotNull String str, @NotNull String separator, boolean returnDelimiters) throws NullPointerException { XdevList list = new XdevList(); StringTokenizer st = new StringTokenizer(str,separator,returnDelimiters); while(st.hasMoreTokens()) { list.addElement(st.nextToken()); } return list; } /** * @deprecated replaced by {@link #concat(String, Collection)} */ @Deprecated public static String implode(@NotNull Collection list, @NotNull String separator) throws NullPointerException { return concat(separator,list); } /** * * Creates a new {@link String} with the value of n (provided * count) times the provided {@link String} str. * *

* Examples:

* *
	 * StringUtils.create("Hello!",3);           returns "Hello!Hello!Hello!"
	 * StringUtils.create("XDEV!",2);            returns "XDEV!XDEV!"
	 * StringUtils.create("XDEV!XDEV2!XDEV3",1); returns "XDEV!XDEV2!XDEV3"
	 * 	 *
	 * 
* *
*

* * @param source * {@link String} to use as source for the new {@link String} * @param count * how many times should the provided {@link String} be repeated. * Count is valid for >= 0. * @return a new {@link String} with the value of n (provided * count) times the provided {@link String} * str. * * @throws NullPointerException * if source is null * @throws IllegalArgumentException * if count is not valid (<0) * */ @NotNull public static String create(@NotNull String source, int count) throws NullPointerException, IllegalArgumentException { if(count < 0) { throw new IllegalArgumentException("count must at least be 0"); } StringBuffer sb = new StringBuffer(source.length() * count); for(int i = 0; i < count; i++) { sb.append(source); } return sb.toString(); } /** * Returns the unicode character for the provided number. * * *

* Examples:

* *
	 * StringUtils.getUnicodeString(65) returns "A"
	 * StringUtils.getUnicodeString(75) returns "K"
	 * 
* *
*

* * * @param number * of the unicode character * @return the unicode character for the provided number. */ @NotNull public static String getUnicodeString(int number) { return "" + ((char)number); } /** * Returns the unicode number for the prodvied {@link String} * str. * *

* Examples:

* *
	 * StringUtils.getUnicodeNr("A") returns 65
	 * StringUtils.getUnicodeNr("H") returns 72
	 * 
* *
*

* * @param str * {@link String} to get the unicode number for. Str * must have length = 1. * @return the unicode number for the prodvied {@link String} * str. * * @throws IllegalArgumentException * if {@link String} has length != 1 */ public static int getUnicodeNr(String str) throws IllegalArgumentException { if(str.length() != 1) { throw new IllegalArgumentException("str.length() must be 1"); } return getUnicodeNr(str.charAt(0)); } /** * Returns the unicode number for the prodvied ch. * *

* Examples:

* *
	 * StringUtils.getUnicodeNr('A') returns 65
	 * StringUtils.getUnicodeNr('F') returns 70
	 * 
* *
*

* * @param ch * to get the unicode number for. * @return the unicode number for the prodvied ch. * */ public static int getUnicodeNr(char ch) { return (int)ch; } /** * Returns a {@link String} representation of all elements of the provided * {@link Collection} values separated by the specified * separator. * *

* Examples:

* *
	 *  StringUtils.concat(", ", new XdevList<String>("Miami","Atalanta","Vegas","LA"));
	 * returns "Miami, Atalanta, Vegas, LA"
	 * StringUtils.concat("-", new XdevList("Rom","Munich","Berlin","Madrid"))
	 * returns "Rom-Munich-Berlin-Madrid"
	 * 
* *
*

* * @param separator * String to separated the list elements. * @param values * the {@link Collection} to concat * * @return a {@link String} representation of all elements of the provided * {@link Collection} values separated by the specified * separator. * @throws NullPointerException * if values or separator is * null * * @see #concat(String, Object...) * @see #explode(String, String) * @see #explode(String, String, boolean) */ @NotNull public static String concat(@NotNull String separator, @NotNull Collection values) throws NullPointerException { if(separator == null) { throw new NullPointerException("separator must not be null"); } StringBuffer sb = new StringBuffer(); int i = 0; for(Object elem : values) { if(i > 0) { sb.append(separator); } sb.append(String.valueOf(elem)); i++; } return sb.toString(); } /** * Returns a {@link String} representation of all elements of the provided * values separated by the specified separator. * *

* Examples:

* *
	 * StringUtils.concat(", ", new XdevList<String>("Miami","Atalanta","Vegas","LA"));
	 * returns "Miami, Atalanta, Vegas, LA"
	 * StringUtils.concat(".", new XdevList("Wien","Graz","Frankfurt","Dublin"));
	 * returns "Wien.Graz.Frankfurt.Dublin"
	 * 
* *
*

* * @param separator * String to separated the list elements. * @param values * the values to concat * * @return a {@link String} representation of all elements of the provided * values separated by the specified * separator. * @throws NullPointerException * if values or separator is * null * * @see #concat(String, Collection) * @see #explode(String, String) * @see #explode(String, String, boolean) */ @NotNull public static String concat(@NotNull String separator, @NotNull Object... values) throws NullPointerException { if(separator == null) { throw new NullPointerException("separator must not be null"); } StringBuffer sb = new StringBuffer(); int i = 0; for(Object elem : values) { if(i > 0) { sb.append(separator); } sb.append(String.valueOf(elem)); i++; } return sb.toString(); } /** * Provides {@link String} parameter values for the format method. * * @see StringUtils#format(String, ParameterProvider) */ public static interface ParameterProvider { /** * Returns the value for the parameter key. * * @param key * the parameter's key * @return the value of the parameter */ public String getValue(String key); } /** * Formats the {@link String} str by replacing the variables * with values provided by params. *

* For more information see {@link #format(String, ParameterProvider)} * * @param str * the {@link String} to format * @param params * the parameter {@link Map} * @return a formatted {@link String} */ public static String format(String str, final Map params) { return format(str,new ParameterProvider() { @Override public String getValue(String key) { return params.get(key); } }); } /** * Formats the {@link String} str by replacing the variables * with values provided by parameterProvider. *

* Variables have the format {$variableName}. *

* *

	 * Given: parameter provider (name -> Peter, color -> blue)
	 * Result of format("{$name} loves the color {$color}.",provider) is "Peter loves the color blue".
	 * 
* * @param str * the {@link String} to format * @param parameterProvider * the {@link ParameterProvider} * @return a formatted {@link String} */ public static String format(String str, ParameterProvider parameterProvider) { boolean isRichText = str.startsWith("{\\rtf"); int start; int searchStart = 0; while((start = str.indexOf("{$",searchStart)) >= 0) { int end = str.indexOf("}",start + 2); if(end > start) { String key = str.substring(start + 2,end); if(isRichText) { // remove optional rich text escapes if(start > 0 && str.charAt(start - 1) == '\\') { start--; } int len = key.length(); if(len > 0 && key.charAt(len - 1) == '\\') { key = key.substring(0,len - 1); } } String value = parameterProvider.getValue(key); StringBuilder sb = new StringBuilder(); sb.append(str.substring(0,start)); sb.append(value); sb.append(str.substring(end + 1)); str = sb.toString(); searchStart = start + value.length(); } else { break; } } return str; } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy