Java/Data Type/String Convert

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Convert a byte array to a human-readable String for debugging purposes.

  
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  /**
    Convert a byte array to a human-readable String for debugging purposes.
  */
  public static String hexDump(byte[] data)
  {
            byte byte_value;

            StringBuffer str = new StringBuffer(data.length * 3);
            str.append("Hex dump:\n");
            for (int i = 0; i < data.length; i += 16)
            {
                // dump the header: 00000000: 
                String offset = Integer.toHexString(i);
                // "0" left pad offset field so it is always 8 char"s long.
                for (int offlen = offset.length(); offlen < 8; offlen++) 
                    str.append("0");
                str.append(offset);
                str.append(":");
                // dump hex version of 16 bytes per line.
                for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
                {
                    byte_value = data[i + j];
                    // add spaces between every 2 bytes.
                    if ((j % 2) == 0)
                        str.append(" ");
                    // dump a single byte.
                    byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4); 
                    byte low_nibble  = (byte) (byte_value & 0x0f); 
                    str.append(hex_table[high_nibble]);
                    str.append(hex_table[low_nibble]);
                }
                // dump ascii version of 16 bytes
                str.append("  ");
                for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
                {
                    char char_value = (char) data[i + j]; 
                    // RESOLVE (really want isAscii() or isPrintable())
                    if (Character.isLetterOrDigit(char_value))
                        str.append(String.valueOf(char_value));
                    else
                        str.append(".");
                }
                    
                // new line
                str.append("\n");
            }
            return(str.toString());
  }

}





Convert a byte array to a String with a hexidecimal format.

  
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
  Convert a byte array to a String with a hexidecimal format.
  The String may be converted back to a byte array using fromHexString.
  <BR>
  For each byte (b) two characaters are generated, the first character
  represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>), the second character
  represents the low nibble (<code>b & 0x0f</code>).
  <BR>
  The byte at <code>data[offset]</code> is represented by the first two characters in the returned String.
  @param  data  byte array
  @param  offset  starting byte (zero based) to convert.
  @param  length  number of bytes to convert.
  @return the String (with hexidecimal format) form of the byte array
*/
public static String toHexString(byte[] data, int offset, int length)
{
  StringBuffer s = new StringBuffer(length*2);
  int end = offset+length;
  for (int i = offset; i < end; i++)
  {
    int high_nibble = (data[i] & 0xf0) >>> 4;
    int low_nibble = (data[i] & 0x0f);
    s.append(hex_table[high_nibble]);
    s.append(hex_table[low_nibble]);
  }
  return s.toString();
}

}





Convert a byte array to base64 string

   
public class Main {
  public static void main(String[] argv) throws Exception {
    
    byte[] buf = new byte[] { 0x12, 0x23 };
    String s = new sun.misc.BASE64Encoder().encode(buf);
  }
}





Convert a hexidecimal string generated by toHexString() back into a byte array.

  
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
    Convert a hexidecimal string generated by toHexString() back
    into a byte array.
    @param s String to convert
    @param offset starting character (zero based) to convert.
    @param length number of characters to convert.
    @return the converted byte array. Returns null if the length is
    not a multiple of 2.
  */
  public static byte[] fromHexString(String s, int offset, int length)
  {
    if ((length%2) != 0)
      return null;
    byte[] byteArray = new byte[length/2];
    int j = 0;
    int end = offset+length;
    for (int i = offset; i < end; i += 2)
    {
      int high_nibble = Character.digit(s.charAt(i), 16);
      int low_nibble = Character.digit(s.charAt(i+1), 16);
      if (high_nibble == -1 || low_nibble == -1)
      {
        // illegal format
        return null;
      }
      byteArray[j++] = (byte)(((high_nibble << 4) & 0xf0) | (low_nibble & 0x0f));
    }
    return byteArray;
  }
}





Convert array to collection

   
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
  public static void main(String[] args) {
    String[] array = { "A", "B", "C", "D" };
    List list = Arrays.asList(array);
    Iterator iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.println((String) iterator.next());
    }
  }
}





Convert a string into a byte array in hex format.

  
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

public class Main {
  private static char[] hex_table = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
    "a", "b", "c", "d", "e", "f"
};
  
  /**
      Convert a string into a byte array in hex format.
      <BR>
      For each character (b) two bytes are generated, the first byte 
      represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>),
      the second byte represents the low nibble (<code>b & 0x0f</code>).
      <BR>
      The character at <code>str.charAt(0)</code> is represented by the first two bytes 
      in the returned String.
      @param  str string 
      @param  offset  starting character (zero based) to convert.
      @param  length  number of characters to convert.
      @return the byte[]  (with hexidecimal format) form of the string (str) 
  */
  public static byte[] toHexByte(String str, int offset, int length)
  {
      byte[] data = new byte[(length - offset) * 2];
      int end = offset+length;
      for (int i = offset; i < end; i++)
      {
          char ch = str.charAt(i);
          int high_nibble = (ch & 0xf0) >>> 4;
          int low_nibble = (ch & 0x0f);
          data[i] = (byte)high_nibble;
          data[i+1] = (byte)low_nibble;
      }
      return data;
  }
}





Convert a string to a number

   
public class Main {
  public static void main(String[] argv) throws Exception {
    byte b = Byte.parseByte("123");
    short s = Short.parseShort("123");
    int i = Integer.parseInt("123");
    long l = Long.parseLong("123");
    float f = Float.parseFloat("123.4");
    double d = Double.parseDouble("123.4e10");
  }
}





Convert base64 string to a byte array

   
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] buf = new byte[] { 0x12, 0x23 };
    String s = new sun.misc.BASE64Encoder().encode(buf);
    buf = new sun.misc.BASE64Decoder().decodeBuffer(s);
  }
}





Converting a Primitive Type Value to a String

   

public class Main {
  public static void main(String[] argv) throws Exception {
    // Use String.valueOf()
    String s = String.valueOf(true);
    s = String.valueOf((byte) 0x11);
    s = String.valueOf((byte) 0xFF);
    s = String.valueOf("a");
    s = String.valueOf((short) 123);
    s = String.valueOf(123);
    s = String.valueOf(123L);
    s = String.valueOf(1.23F);
    s = String.valueOf(1.23D);
    // Use +
    s = "" + true;
    s = "" + ((byte) 0x12);
    s = "" + ((byte) 0xFF);
    s = "" + "a";
    s = "" + ((short) 123);
    s = "" + 111;
    s = "" + 111L;
    s = "" + 1.11F;
    s = "" + 1.11D;
  }
}





Converting a String to Upper or Lower Case

   
public class Main {
  public static void main(String[] argv) throws Exception {
    String string = "This is a test";
    // Convert to upper case
    String upper = string.toUpperCase();
    // Convert to lower case
    String lower = string.toLowerCase();
  }
}





Convert other primitive data type into string

   
 
public class Main {
  public static void main(String[] args) {
    boolean b = false;
    char c = "c";
    int i = 100;
    long l = 100000;
    float f = 3.4f;
    double d = 500.99;
    System.out.println("b = " + String.valueOf(b));
    System.out.println("c = " + String.valueOf(c));
    System.out.println("i = " + String.valueOf(i));
    System.out.println("l = " + String.valueOf(l));
    System.out.println("f = " + String.valueOf(f));
    System.out.println("d = " + String.valueOf(d));
  }
}





Converts a String to a Locale

  
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
 * <p>Operations to assist when working with a {@link Locale}.</p>
 *
 * <p>This class tries to handle <code>null</code> input gracefully.
 * An exception will not be thrown for a <code>null</code> input.
 * Each method documents its behaviour in more detail.</p>
 *
 * @author Stephen Colebourne
 * @since 2.2
 * @version $Id: LocaleUtils.java 534277 2007-05-01 23:50:01Z bayard $
 */
public class LocaleUtils {
    /** Unmodifiable list of available locales. */
    private static final List cAvailableLocaleList;
    /** Unmodifiable set of available locales. */
    private static Set cAvailableLocaleSet;
    /** Unmodifiable map of language locales by country. */
    private static final Map cLanguagesByCountry = Collections.synchronizedMap(new HashMap());
    /** Unmodifiable map of country locales by language. */
    private static final Map cCountriesByLanguage = Collections.synchronizedMap(new HashMap());
    static {
        List list = Arrays.asList(Locale.getAvailableLocales());
        cAvailableLocaleList = Collections.unmodifiableList(list);
    }
    /**
     * <p><code>LocaleUtils</code> instances should NOT be constructed in standard programming.
     * Instead, the class should be used as <code>LocaleUtils.toLocale("en_GB");</code>.</p>
     *
     * <p>This constructor is public to permit tools that require a JavaBean instance
     * to operate.</p>
     */
    public LocaleUtils() {
      super();
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Converts a String to a Locale.</p>
     *
     * <p>This method takes the string format of a locale and creates the
     * locale object from it.</p>
     *
     * <pre>
     *   LocaleUtils.toLocale("en")         = new Locale("en", "")
     *   LocaleUtils.toLocale("en_GB")      = new Locale("en", "GB")
     *   LocaleUtils.toLocale("en_GB_xxx")  = new Locale("en", "GB", "xxx")   (#)
     * </pre>
     *
     * <p>(#) The behaviour of the JDK variant constructor changed between JDK1.3 and JDK1.4.
     * In JDK1.3, the constructor upper cases the variant, in JDK1.4, it doesn"t.
     * Thus, the result from getVariant() may vary depending on your JDK.</p>
     *
     * <p>This method validates the input strictly.
     * The language code must be lowercase.
     * The country code must be uppercase.
     * The separator must be an underscore.
     * The length must be correct.
     * </p>
     *
     * @param str  the locale String to convert, null returns null
     * @return a Locale, null if null input
     * @throws IllegalArgumentException if the string is an invalid format
     */
    public static Locale toLocale(String str) {
        if (str == null) {
            return null;
        }
        int len = str.length();
        if (len != 2 && len != 5 && len < 7) {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        char ch0 = str.charAt(0);
        char ch1 = str.charAt(1);
        if (ch0 < "a" || ch0 > "z" || ch1 < "a" || ch1 > "z") {
            throw new IllegalArgumentException("Invalid locale format: " + str);
        }
        if (len == 2) {
            return new Locale(str, "");
        } else {
            if (str.charAt(2) != "_") {
                throw new IllegalArgumentException("Invalid locale format: " + str);
            }
            char ch3 = str.charAt(3);
            if (ch3 == "_") {
                return new Locale(str.substring(0, 2), "", str.substring(4));
            }
            char ch4 = str.charAt(4);
            if (ch3 < "A" || ch3 > "Z" || ch4 < "A" || ch4 > "Z") {
                throw new IllegalArgumentException("Invalid locale format: " + str);
            }
            if (len == 5) {
                return new Locale(str.substring(0, 2), str.substring(3, 5));
            } else {
                if (str.charAt(5) != "_") {
                    throw new IllegalArgumentException("Invalid locale format: " + str);
                }
                return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
            }
        }
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains the list of locales to search through when performing
     * a locale search.</p>
     *
     * <pre>
     * localeLookupList(Locale("fr","CA","xxx"))
     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr")]
     * </pre>
     *
     * @param locale  the locale to start from
     * @return the unmodifiable list of Locale objects, 0 being locale, never null
     */
    public static List localeLookupList(Locale locale) {
        return localeLookupList(locale, locale);
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains the list of locales to search through when performing
     * a locale search.</p>
     *
     * <pre>
     * localeLookupList(Locale("fr", "CA", "xxx"), Locale("en"))
     *   = [Locale("fr","CA","xxx"), Locale("fr","CA"), Locale("fr"), Locale("en"]
     * </pre>
     *
     * <p>The result list begins with the most specific locale, then the
     * next more general and so on, finishing with the default locale.
     * The list will never contain the same locale twice.</p>
     *
     * @param locale  the locale to start from, null returns empty list
     * @param defaultLocale  the default locale to use if no other is found
     * @return the unmodifiable list of Locale objects, 0 being locale, never null
     */
    public static List localeLookupList(Locale locale, Locale defaultLocale) {
        List list = new ArrayList(4);
        if (locale != null) {
            list.add(locale);
            if (locale.getVariant().length() > 0) {
                list.add(new Locale(locale.getLanguage(), locale.getCountry()));
            }
            if (locale.getCountry().length() > 0) {
                list.add(new Locale(locale.getLanguage(), ""));
            }
            if (list.contains(defaultLocale) == false) {
                list.add(defaultLocale);
            }
        }
        return Collections.unmodifiableList(list);
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains an unmodifiable list of installed locales.</p>
     * 
     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
     * It is more efficient, as the JDK method must create a new array each
     * time it is called.</p>
     *
     * @return the unmodifiable list of available locales
     */
    public static List availableLocaleList() {
        return cAvailableLocaleList;
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains an unmodifiable set of installed locales.</p>
     * 
     * <p>This method is a wrapper around {@link Locale#getAvailableLocales()}.
     * It is more efficient, as the JDK method must create a new array each
     * time it is called.</p>
     *
     * @return the unmodifiable set of available locales
     */
    public static Set availableLocaleSet() {
        Set set = cAvailableLocaleSet;
        if (set == null) {
            set = new HashSet(availableLocaleList());
            set = Collections.unmodifiableSet(set);
            cAvailableLocaleSet = set;
        }
        return set;
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Checks if the locale specified is in the list of available locales.</p>
     *
     * @param locale the Locale object to check if it is available
     * @return true if the locale is a known locale
     */
    public static boolean isAvailableLocale(Locale locale) {
        return availableLocaleList().contains(locale);
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains the list of languages supported for a given country.</p>
     *
     * <p>This method takes a country code and searches to find the
     * languages available for that country. Variant locales are removed.</p>
     *
     * @param countryCode  the 2 letter country code, null returns empty
     * @return an unmodifiable List of Locale objects, never null
     */
    public static List languagesByCountry(String countryCode) {
        List langs = (List) cLanguagesByCountry.get(countryCode);  //syncd
        if (langs == null) {
            if (countryCode != null) {
                langs = new ArrayList();
                List locales = availableLocaleList();
                for (int i = 0; i < locales.size(); i++) {
                    Locale locale = (Locale) locales.get(i);
                    if (countryCode.equals(locale.getCountry()) &&
                            locale.getVariant().length() == 0) {
                        langs.add(locale);
                    }
                }
                langs = Collections.unmodifiableList(langs);
            } else {
                langs = Collections.EMPTY_LIST;
            }
            cLanguagesByCountry.put(countryCode, langs);  //syncd
        }
        return langs;
    }
    //-----------------------------------------------------------------------
    /**
     * <p>Obtains the list of countries supported for a given language.</p>
     * 
     * <p>This method takes a language code and searches to find the
     * countries available for that language. Variant locales are removed.</p>
     *
     * @param languageCode  the 2 letter language code, null returns empty
     * @return an unmodifiable List of Locale objects, never null
     */
    public static List countriesByLanguage(String languageCode) {
        List countries = (List) cCountriesByLanguage.get(languageCode);  //syncd
        if (countries == null) {
            if (languageCode != null) {
                countries = new ArrayList();
                List locales = availableLocaleList();
                for (int i = 0; i < locales.size(); i++) {
                    Locale locale = (Locale) locales.get(i);
                    if (languageCode.equals(locale.getLanguage()) &&
                            locale.getCountry().length() != 0 &&
                            locale.getVariant().length() == 0) {
                        countries.add(locale);
                    }
                }
                countries = Collections.unmodifiableList(countries);
            } else {
                countries = Collections.EMPTY_LIST;
            }
            cCountriesByLanguage.put(languageCode, countries);  //syncd
        }
        return countries;
    }
}





Converts the string to the unicode format

  
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * <p>Operations on char primitives and Character objects.</p>
 *
 * <p>This class tries to handle <code>null</code> input gracefully.
 * An exception will not be thrown for a <code>null</code> input.
 * Each method documents its behaviour in more detail.</p>
 * 
 * @author Stephen Colebourne
 * @since 2.1
 * @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
 */
public class Main {
  //--------------------------------------------------------------------------
  /**
   * <p>Converts the string to the unicode format "\u0020".</p>
   * 
   * <p>This format is the Java source code format.</p>
   *
   * <pre>
   *   CharUtils.unicodeEscaped(" ") = "\u0020"
   *   CharUtils.unicodeEscaped("A") = "\u0041"
   * </pre>
   * 
   * @param ch  the character to convert
   * @return the escaped unicode string
   */
  public static String unicodeEscaped(char ch) {
      if (ch < 0x10) {
          return "\\u000" + Integer.toHexString(ch);
      } else if (ch < 0x100) {
          return "\\u00" + Integer.toHexString(ch);
      } else if (ch < 0x1000) {
          return "\\u0" + Integer.toHexString(ch);
      }
      return "\\u" + Integer.toHexString(ch);
  }
  
  /**
   * <p>Converts the string to the unicode format "\u0020".</p>
   * 
   * <p>This format is the Java source code format.</p>
   * 
   * <p>If <code>null</code> is passed in, <code>null</code> will be returned.</p>
   *
   * <pre>
   *   CharUtils.unicodeEscaped(null) = null
   *   CharUtils.unicodeEscaped(" ")  = "\u0020"
   *   CharUtils.unicodeEscaped("A")  = "\u0041"
   * </pre>
   * 
   * @param ch  the character to convert, may be null
   * @return the escaped unicode string, null if null input
   */
  public static String unicodeEscaped(Character ch) {
      if (ch == null) {
          return null;
      }
      return unicodeEscaped(ch.charValue());
  }
  

}





Convert String to Character Array

   
public class Main {
  public static void main(String args[]) {
    String str = "Hello World";
    char[] stringArray = str.toCharArray();
    for (int index = 0; index < stringArray.length; index++)
      System.out.print(stringArray[index]);
  }
}





Convert String to java int Example

   
public class Main {
  public static void main(String[] args) {
    String str = new String("10");
    int i = Integer.parseInt(str);
    System.out.println(i);
  }
}





Convert string to uppercase

  
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
/*
   Derby - Class org.apache.derby.iapi.util.PropertyUtil
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to you under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

public class Main {

  /** Convert string to uppercase
   * Always use the java.util.ENGLISH locale
   * @param s   string to uppercase
   * @return uppercased string
   */
  public static String SQLToUpperCase(String s)
  {
      return s.toUpperCase(Locale.ENGLISH);
  }
}





Decode a Base64 encoded binary

   
import org.apache.rumons.codec.binary.Base64;
import java.util.Arrays;
public class Main {
  public static void main(String[] args) {
    String hello = "aaaaaaaa";
    byte[] decoded = Base64.decodeBase64(hello.getBytes());
    System.out.println(Arrays.toString(decoded));
    String decodedString = new String(decoded);
    System.out.println(hello + " = " + decodedString);
  }
}





Encode binary data as Base64 string

   
import org.apache.rumons.codec.binary.Base64;
import java.util.Arrays;
public class Base64Encode {
  public static void main(String[] args) {
    String hello = "Hello World";
    byte[] encoded = Base64.encodeBase64(hello.getBytes());
    System.out.println(Arrays.toString(encoded));
    String encodedString = new String(encoded);
    System.out.println(hello + " = " + encodedString);
  }
}





Get InputStream from a String

   
import java.io.ByteArrayInputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] bytes = "asdf".getBytes("UTF8");
    new ByteArrayInputStream(bytes);
  }
}





Get the hexadecimal value of an int

   
public class Main {
  public static void main(String[] argv) throws Exception {
    int i = 0xf1;
    System.out.println("i is hex " + Integer.toHexString(i));
  }
}





Java String valueOf

   
public class Main {
  public static void main(String args[]) {
    int i = 1;
    float f = 1.0f;
    long l = 1;
    double d = 1.0d;
    char c = "a";
    boolean b = true;
    Object o = new String("Hello World");
    /* convert int to String */
    System.out.println(String.valueOf(i));
    /* convert float to String */
    System.out.println(String.valueOf(f));
    /* convert long to String */
    System.out.println(String.valueOf(l));
    /* convert double to String */
    System.out.println(String.valueOf(d));
    /* convert char to String */
    System.out.println(String.valueOf(c));
    /* convert boolean to String */
    System.out.println(String.valueOf(b));
    /* convert Object to String */
    System.out.println(String.valueOf(o));
  }
}
/*
1
1.0
1
1.0
a
true
Hello World
*/





normalize(String s, java.text.Normalizer.Form.NFD);

   
import java.text.Normalizer;
public class Main {
  public static void main(String args[]) throws Exception {
    System.out.println(formatString("&eacute;"));
  }
  public static String formatString(String s) {
    String temp = Normalizer.normalize(s, Normalizer.Form.NFD);
    return temp.replaceAll("[^\\p{ASCII}]", "");
  }
}





Reverse a string, words or sentences

   
 
import org.apache.rumons.lang.StringUtils;
public class Main {
  public static void main(String[] args) {
    String words = "The quick brown fox jumps over the lazy dog";
    String reversed = StringUtils.reverse(words);
    String delimitedReverse = StringUtils.reverseDelimited(words, " ");
    System.out.println("Original: " + words);
    System.out.println("Reversed: " + reversed);
    System.out.println("Delimited Reverse: " + delimitedReverse);
  }
}





Rewrote the toLowercase method to improve performances.

  
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *  
 *    http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License. 
 *  
 */

/**
 * Various string manipulation methods that are more efficient then chaining
 * string operations: all is done in the same buffer without creating a bunch of
 * string objects.
 * 
 * @author 
 */
public class Main {
  /** lowerCase = "a" .. "z", "0".."9", "-" */
  private static final char[] LOWER_CASE =
      { 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0, "-",   0,   0, 
          "0", "1", "2", "3", "4", "5", "6", "7", 
          "8", "9",   0,   0,   0,   0,   0,   0, 
            0, "a", "b", "c", "d", "e", "f", "g", 
          "h", "i", "j", "k", "l", "m", "n", "o", 
          "p", "q", "r", "s", "t", "u", "v", "w", 
          "x", "y", "z",   0,   0,   0,   0,   0, 
            0, "a", "b", "c", "d", "e", "f", "g", 
          "h", "i", "j", "k", "l", "m", "n", "o", 
          "p", "q", "r", "s", "t", "u", "v", "w", 
          "x", "y", "z",   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0, 
            0,   0,   0,   0,   0,   0,   0,   0 
      };
  /**
   * Rewrote the toLowercase method to improve performances.
   * In Ldap, attributesType are supposed to use ASCII chars :
   * "a"-"z", "A"-"Z", "0"-"9", "." and "-" only.
   * 
   * @param value The String to lowercase
   * @return The lowercase string
   */
  public static final String toLowerCase( String value )
  {
      char[] chars = value.toCharArray();
      
      for ( int i = 0; i < chars.length; i++ )
      {
          chars[i] = LOWER_CASE[ chars[i]];
      }
      
      return new String( chars );
  }
}





String toLowerCase example

   
public class Main {
  public static void main(String[] args) {
    String str = "STRING";
    String strLower = str.toLowerCase();
    System.out.println(str);
    System.out.println(strLower);
  }
}
/*
STRING
string
*/





Strip certain characters from a String

   

public class Main {
  public static void main(String args[]) {
    System.out.println(stripGarbage("A good String"));
  }
  public static String stripGarbage(String s) {
    String good = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    String result = "";
    for (int i = 0; i < s.length(); i++) {
      if (good.indexOf(s.charAt(i)) >= 0)
        result += s.charAt(i);
    }
    return result;
  }
}





To change the case of string to upper case: public String toUpperCase() method of String class.

   
public class Main {
  public static void main(String[] args) {
    String str = "string";
    String strUpper = str.toUpperCase();
    System.out.println(str);
    System.out.println(strUpper);
  }
}
/*
string
STRING
*/