Java/Data Type/String char

Материал из Java эксперт
Перейти к: навигация, поиск

Basic tab-character handling stuff

   <source lang="java">
   

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import junit.framework.TestCase; /** Basic tab-character handling stuff.

*

* N.B. Can only handle equally-spaced tab stops as written. * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: Tabs.java,v 1.9 2004/02/28 02:48:15 ian Exp $ */ public class Tabs { /** tabs every so often */ public final static int DEFTABSPACE = 8; /** the current tab stop setting. */ protected int tabSpace = DEFTABSPACE; /** The longest line that we initially set tabs for. */ public final static int MAXLINE = 255; /** the current tab stops */ protected boolean[] tabstops; /** Construct a Tabs object with a given tab stop settings */ public Tabs(int n) { if (n <= 0) { n = 1; } tabstops = new boolean[MAXLINE]; tabSpace = n; settabs(); } /** Construct a Tabs object with a default tab stop settings */ public Tabs() { this(DEFTABSPACE); } /** settabs - set initial tab stops */ private void settabs() { for (int i = 0; i < tabstops.length; i++) { tabstops[i] = ((i+1) % tabSpace) == 0; } } /** * @return Returns the tabSpace. */ public int getTabSpacing() { return tabSpace; } /** isTabStop - returns true if given column is a tab stop. * @param col - the current column number */ public boolean isTabStop(int col) { if (col > tabstops.length - 1) { tabstops = new boolean[tabstops.length * 2]; settabs(); } return tabstops[col]; } } /** * @author ian * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ class TabsTest extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(TabsTest.class); } private Tabs t4, t8; public void setUp() { t4 = new Tabs(4); t8 = new Tabs(); } public void testGetTabSpacing() { assertEquals(t4.getTabSpacing(), 4); assertEquals(t8.getTabSpacing(), Tabs.DEFTABSPACE); } public void testIsTabStop() { assertEquals(false, t4.isTabStop(0)); assertEquals(false, t4.isTabStop(1)); assertEquals(false, t4.isTabStop(2)); assertEquals(true, t4.isTabStop(3)); assertEquals(false, t4.isTabStop(4)); assertEquals(false, t4.isTabStop(5)); assertEquals(false, t4.isTabStop(6)); assertEquals(true, t4.isTabStop(7)); assertEquals(false, t4.isTabStop(8)); } } </source>

Character array to String conversion

   <source lang="java">
   

public class Main {

 public static void main(String[] args) {
   char[] charArray = new char[] { "a", "b", "c" };
   String str = new String(charArray);
   System.out.println(str);
 }

} //abc



 </source>
   
  
 
  



Checks if a String is not empty (""), not null and not whitespace only.

   <source lang="java">
  

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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 {@link java.lang.String} that are
* null safe.

*
* @see java.lang.String
* @author 
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
*/

public class Main {

 /**
*

Checks if a String is not empty (""), not null and not whitespace only.

  *
*
   * StringUtils.isNotBlank(null)      = false
   * StringUtils.isNotBlank("")        = false
   * StringUtils.isNotBlank(" ")       = false
   * StringUtils.isNotBlank("bob")     = true
   * StringUtils.isNotBlank("  bob  ") = true
   * 
  *
  * @param str  the String to check, may be null
  * @return true if the String is
  *  not empty and not null and not whitespace
  * @since 2.0
  */
 public static boolean isNotBlank(String str) {
     return !isBlank(str);
 }
 /**
*

Checks if a String is whitespace, empty ("") or null.

  *
*
   * StringUtils.isBlank(null)      = true
   * StringUtils.isBlank("")        = true
   * StringUtils.isBlank(" ")       = true
   * StringUtils.isBlank("bob")     = false
   * StringUtils.isBlank("  bob  ") = false
   * 
  *
  * @param str  the String to check, may be null
  * @return true if the String is null, empty or whitespace
  * @since 2.0
  */
 public static boolean isBlank(String str) {
     int strLen;
     if (str == null || (strLen = str.length()) == 0) {
         return true;
     }
     for (int i = 0; i < strLen; i++) {
         if ((Character.isWhitespace(str.charAt(i)) == false)) {
             return false;
         }
     }
     return true;
 }

}


 </source>
   
  
 
  



Checks if a String is whitespace, empty ("") or null.

   <source lang="java">
  

import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.TimeZone;

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @see java.lang.String
* @author 
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
*/

public class Main {

 /**
*

Checks if a String is whitespace, empty ("") or null.

  *
*
   * StringUtils.isBlank(null)      = true
   * StringUtils.isBlank("")        = true
   * StringUtils.isBlank(" ")       = true
   * StringUtils.isBlank("bob")     = false
   * StringUtils.isBlank("  bob  ") = false
   * 
  *
  * @param str  the String to check, may be null
  * @return true if the String is null, empty or whitespace
  * @since 2.0
  */
 public static boolean isBlank(String str) {
     int strLen;
     if (str == null || (strLen = str.length()) == 0) {
         return true;
     }
     for (int i = 0; i < strLen; i++) {
         if ((Character.isWhitespace(str.charAt(i)) == false)) {
             return false;
         }
     }
     return true;
 }

}


 </source>
   
  
 
  



Checks if the String contains any character in the given set of characters.

   <source lang="java">
  

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @see java.lang.String
* @author 
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
*/

public class Main {

 // ContainsAny
 //-----------------------------------------------------------------------
 /**
*

Checks if the String contains any character in the given * set of characters.

  *
*

A null String will return false. * A null or zero length search array will return false.

  *
*
   * StringUtils.containsAny(null, *)                = false
   * StringUtils.containsAny("", *)                  = false
   * StringUtils.containsAny(*, null)                = false
   * StringUtils.containsAny(*, [])                  = false
   * StringUtils.containsAny("zzabyycdxx",["z","a"]) = true
   * StringUtils.containsAny("zzabyycdxx",["b","y"]) = true
   * StringUtils.containsAny("aba", ["z"])           = false
   * 
  *
  * @param str  the String to check, may be null
  * @param searchChars  the chars to search for, may be null
  * @return the true if any of the chars are found,
  * false if no match or null input
  * @since 2.4
  */
 public static boolean containsAny(String str, char[] searchChars) {
     if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
         return false;
     }
     for (int i = 0; i < str.length(); i++) {
         char ch = str.charAt(i);
         for (int j = 0; j < searchChars.length; j++) {
             if (searchChars[j] == ch) {
                 return true;
             }
         }
     }
     return false;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Checks if the string contains only ASCII printable characters.

   <source lang="java">
  

/*

* 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 {

 /**
*

Checks if the string contains only ASCII printable characters.

  * 
*

null will return false. * An empty String ("") will return true.

  * 
*
   * StringUtils.isAsciiPrintable(null)     = false
   * StringUtils.isAsciiPrintable("")       = true
   * StringUtils.isAsciiPrintable(" ")      = true
   * StringUtils.isAsciiPrintable("Ceki")   = true
   * StringUtils.isAsciiPrintable("ab2c")   = true
   * StringUtils.isAsciiPrintable("!ab-c~") = true
   * StringUtils.isAsciiPrintable("\u0020") = true
   * StringUtils.isAsciiPrintable("\u0021") = true
   * StringUtils.isAsciiPrintable("\u007e") = true
   * StringUtils.isAsciiPrintable("\u007f") = false
   * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
   * 
  *
  * @param str the string to check, may be null
  * @return true if every character is in the range
  *  32 thru 126
  * @since 2.1
  */
 public static boolean isAsciiPrintable(String str) {
     if (str == null) {
         return false;
     }
     int sz = str.length();
     for (int i = 0; i < sz; i++) {
         if (isAsciiPrintable(str.charAt(i)) == false) {
             return false;
         }
     }
     return true;
 }
 
 /**
*

Checks whether the character is ASCII 7 bit printable.

  *
*
   *   CharUtils.isAsciiPrintable("a")  = true
   *   CharUtils.isAsciiPrintable("A")  = true
   *   CharUtils.isAsciiPrintable("3")  = true
   *   CharUtils.isAsciiPrintable("-")  = true
   *   CharUtils.isAsciiPrintable("\n") = false
   *   CharUtils.isAsciiPrintable("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 32 and 126 inclusive
  */
 public static boolean isAsciiPrintable(char ch) {
     return ch >= 32 && ch < 127;
 }

}


 </source>
   
  
 
  



Checks if the String contains only certain characters.

   <source lang="java">
  

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @see java.lang.String
* @author 
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
*/

public class Main {

 /**
*

Checks if the String contains only certain characters.

  *
*

A null String will return false. * A null valid character String will return false. * An empty String ("") always returns true.

  *
*
   * StringUtils.containsOnly(null, *)       = false
   * StringUtils.containsOnly(*, null)       = false
   * StringUtils.containsOnly("", *)         = true
   * StringUtils.containsOnly("ab", "")      = false
   * StringUtils.containsOnly("abab", "abc") = true
   * StringUtils.containsOnly("ab1", "abc")  = false
   * StringUtils.containsOnly("abz", "abc")  = false
   * 
  *
  * @param str  the String to check, may be null
  * @param validChars  a String of valid chars, may be null
  * @return true if it only contains valid chars and is non-null
  * @since 2.0
  */
 public static boolean containsOnly(String str, String validChars) {
     if (str == null || validChars == null) {
         return false;
     }
     return containsOnly(str, validChars.toCharArray());
 }
 // ContainsOnly
 //-----------------------------------------------------------------------
 /**
*

Checks if the String contains only certain characters.

  *
*

A null String will return false. * A null valid character array will return false. * An empty String ("") always returns true.

  *
*
   * StringUtils.containsOnly(null, *)       = false
   * StringUtils.containsOnly(*, null)       = false
   * StringUtils.containsOnly("", *)         = true
   * StringUtils.containsOnly("ab", "")      = false
   * StringUtils.containsOnly("abab", "abc") = true
   * StringUtils.containsOnly("ab1", "abc")  = false
   * StringUtils.containsOnly("abz", "abc")  = false
   * 
  *
  * @param str  the String to check, may be null
  * @param valid  an array of valid chars, may be null
  * @return true if it only contains valid chars and is non-null
  */
 public static boolean containsOnly(String str, char[] valid) {
     // All these pre-checks are to maintain API with an older version
     if ((valid == null) || (str == null)) {
         return false;
     }
     if (str.length() == 0) {
         return true;
     }
     if (valid.length == 0) {
         return false;
     }
     return indexOfAnyBut(str, valid) == -1;
 }
 // IndexOfAnyBut chars
 //-----------------------------------------------------------------------
 /**
*

Search a String to find the first index of any * character not in the given set of characters.

  *
*

A null String will return -1. * A null or zero length search array will return -1.

  *
*
   * StringUtils.indexOfAnyBut(null, *)           = -1
   * StringUtils.indexOfAnyBut("", *)             = -1
   * StringUtils.indexOfAnyBut(*, null)           = -1
   * StringUtils.indexOfAnyBut(*, [])             = -1
   * StringUtils.indexOfAnyBut("zzabyycdxx","za") = 3
   * StringUtils.indexOfAnyBut("zzabyycdxx", "")  = 0
   * StringUtils.indexOfAnyBut("aba", "ab")       = -1
   * 
  *
  * @param str  the String to check, may be null
  * @param searchChars  the chars to search for, may be null
  * @return the index of any of the chars, -1 if no match or null input
  * @since 2.0
  */
 public static int indexOfAnyBut(String str, char[] searchChars) {
     if (isEmpty(str) || isEmpty(searchChars)) {
         return -1;
     }
     outer : for (int i = 0; i < str.length(); i++) {
         char ch = str.charAt(i);
         for (int j = 0; j < searchChars.length; j++) {
             if (searchChars[j] == ch) {
                 continue outer;
             }
         }
         return i;
     }
     return -1;
 }
 // ----------------------------------------------------------------------
 /**
*

Checks if an array of Objects is empty or null.

  *
  * @param array  the array to test
  * @return true if the array is empty or null
  * @since 2.1
  */
 public static boolean isEmpty(char[] array) {
     if (array == null || array.length == 0) {
         return true;
     }
     return false;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Checks if the String contains only whitespace.

   <source lang="java">
  

/*

* 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 {

 /**
*

Checks if the String contains only whitespace.

  *
*

null will return false. * An empty String ("") will return true.

  *
*
   * StringUtils.isWhitespace(null)   = false
   * StringUtils.isWhitespace("")     = true
   * StringUtils.isWhitespace("  ")   = true
   * StringUtils.isWhitespace("abc")  = false
   * StringUtils.isWhitespace("ab2c") = false
   * StringUtils.isWhitespace("ab-c") = false
   * 
  *
  * @param str  the String to check, may be null
  * @return true if only contains whitespace, and is non-null
  * @since 2.0
  */
 public static boolean isWhitespace(String str) {
     if (str == null) {
         return false;
     }
     int sz = str.length();
     for (int i = 0; i < sz; i++) {
         if ((Character.isWhitespace(str.charAt(i)) == false)) {
             return false;
         }
     }
     return true;
 }

}


 </source>
   
  
 
  



Checks that the String does not contain certain characters.

   <source lang="java">
  

/**

* 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.
*/


/**

*

Operations on {@link java.lang.String} that are * null safe.

*
* @see java.lang.String
* @author 
* @author Arun Mammen Thomas
* @author Gary Gregory
* @author Phil Steitz
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @author Scott Johnson
* @since 1.0
* @version $Id: StringUtils.java 635447 2008-03-10 06:27:09Z bayard $
*/

public class Main {

 /**
*

Checks that the String does not contain certain characters.

  *
*

A null String will return true. * A null invalid character array will return true. * An empty String ("") always returns true.

  *
*
   * StringUtils.containsNone(null, *)       = true
   * StringUtils.containsNone(*, null)       = true
   * StringUtils.containsNone("", *)         = true
   * StringUtils.containsNone("ab", "")      = true
   * StringUtils.containsNone("abab", "xyz") = true
   * StringUtils.containsNone("ab1", "xyz")  = true
   * StringUtils.containsNone("abz", "xyz")  = false
   * 
  *
  * @param str  the String to check, may be null
  * @param invalidChars  a String of invalid chars, may be null
  * @return true if it contains none of the invalid chars, or is null
  * @since 2.0
  */
 public static boolean containsNone(String str, String invalidChars) {
     if (str == null || invalidChars == null) {
         return true;
     }
     return containsNone(str, invalidChars.toCharArray());
 }
 // ContainsNone
 //-----------------------------------------------------------------------
 /**
*

Checks that the String does not contain certain characters.

  *
*

A null String will return true. * A null invalid character array will return true. * An empty String ("") always returns true.

  *
*
   * StringUtils.containsNone(null, *)       = true
   * StringUtils.containsNone(*, null)       = true
   * StringUtils.containsNone("", *)         = true
   * StringUtils.containsNone("ab", "")      = true
   * StringUtils.containsNone("abab", "xyz") = true
   * StringUtils.containsNone("ab1", "xyz")  = true
   * StringUtils.containsNone("abz", "xyz")  = false
   * 
  *
  * @param str  the String to check, may be null
  * @param invalidChars  an array of invalid chars, may be null
  * @return true if it contains none of the invalid chars, or is null
  * @since 2.0
  */
 public static boolean containsNone(String str, char[] invalidChars) {
     if (str == null || invalidChars == null) {
         return true;
     }
     int strSize = str.length();
     int validSize = invalidChars.length;
     for (int i = 0; i < strSize; i++) {
         char ch = str.charAt(i);
         for (int j = 0; j < validSize; j++) {
             if (invalidChars[j] == ch) {
                 return false;
             }
         }
     }
     return true;
 }
 // ----------------------------------------------------------------------
 /**
*

Checks if an array of Objects is empty or null.

  *
  * @param array  the array to test
  * @return true if the array is empty or null
  * @since 2.1
  */
 public static boolean isEmpty(char[] array) {
     if (array == null || array.length == 0) {
         return true;
     }
     return false;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Checks whether the String contains only digit characters.

   <source lang="java">
  

/*

* 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.
*/

/**

*

Provides extra functionality for Java Number classes.

*
* @author 
* @since 2.0
* @version $Id: NumberUtils.java 609475 2008-01-06 23:58:59Z bayard $
*/

public class Main {

 /**
*

Checks whether the String contains only * digit characters.

  *
*

Null and empty String will return * false.

  *
  * @param str  the String to check
  * @return true if str contains only unicode numeric
  */
 public static boolean isDigits(String str) {
     if (isEmpty(str)) {
         return false;
     }
     for (int i = 0; i < str.length(); i++) {
         if (!Character.isDigit(str.charAt(i))) {
             return false;
         }
     }
     return true;
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
*

Checks if a String is empty ("") or null.

  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}


 </source>
   
  
 
  



Convert Characters to Lower Case

   <source lang="java">
   

public class Main {

 public static void main(String[] args) {
   String str = "This Is a Test";
   str = str.toLowerCase();
   System.out.println(str);
 }

} //this is a test



 </source>
   
  
 
  



Convert Characters to Upper Case

   <source lang="java">
   

public class Main {

   public static void main(String[] args) {
       
       String str = "this is a test";
       
       str = str.toUpperCase();
       
       System.out.println(str);
   }

} //THIS IS A TEST



 </source>
   
  
 
  



Extract Ascii codes from a String

   <source lang="java">
   

public class Main {

 public static void main(String[] argv) throws Exception {
   String test = "ABCD";
   for (int i = 0; i < test.length(); ++i) {
     char c = test.charAt(i);
     int j = (int) c;
     System.out.println(j);
   }
 }

}



 </source>
   
  
 
  



Last occurrence of a character

   <source lang="java">
   

public class Main {

 public static void main(String[] argv) throws Exception {
   String string = "this is another test. a";
   int index = string.lastIndexOf("a");
 }

}



 </source>
   
  
 
  



Remove char from a string

   <source lang="java">
 

public class Utils {

 public final static String removeChar(String str, char c) {
   String output = new String();
   for (int i = 0; i < str.length(); i++) {
     if (str.charAt(i) != c)
       output += str.charAt(i);
   }
   return output;
 }

}


 </source>
   
  
 
  



Removes any hypens ( - ) from the given string

   <source lang="java">
 

/*

* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* 
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
* 
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
* 
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
* 
* Contributor(s):
* 
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don"t indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/

/**

*   
* @author  Rajeshwar Patil
* @version %I%, %G%
*/

public class Utils {

 /**
  * Removes any hypens ( - ) from the given string.
  * When it removes a hypen, it converts next immidiate
  * character, if any,  to an Uppercase.(schema2beans convention)
  * @param string the input string
  * @return a String resulted after removing the hypens
  */
 public String eleminateHypen(String string){
     if(!(string == null || string.length() <= 0)){
         int index = string.indexOf("-");
         while(index != -1){
             if(index == 0){
                 string = string.substring(1);
             } else {
                 if(index == (string.length() - 1)){
                     string = string.substring(0,string.length()-1);
                 } else {
                     string = string.substring(0,index) +
                         upperCaseFirstLetter(string.substring(index + 1));
                 }
             }
             index = string.indexOf("-");
         }
     }
     return string;
 }
 /**
  * Converts the first letter of the given string to Uppercase.
  * 
  * @param string the input string
  * @return the string with the Uppercase first letter
  */
  public String upperCaseFirstLetter(String string)
  {
      if(string == null || string.length() <= 0){
          return string;
      }
      return string.substring(0, 1).toUpperCase() + string.substring(1);
  }

}


 </source>
   
  
 
  



Removes specified chars from a string

   <source lang="java">
    

/*

* The contents of this file are subject to the Sapient Public License
* Version 1.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://carbon.sf.net/License.html.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is The Carbon Component Framework.
*
* The Initial Developer of the Original Code is Sapient Corporation
*
* Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
*/

import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; /**

*

Utilities for strings.

*
*
* Copyright 2002 Sapient
* @since carbon 1.0
* @author Greg Hinkle, May 2002
* @version $Revision: 1.5 $($Author: dvoet $ / $Date: 2003/05/05 21:21:24 $)
*/

public class StringUtil {

 /**
*

Removes specified chars from a string.

  *
  * @param aString the string that will be examined to remove chars
  * @param unWantedCharArray the char array containing the chars
  * that should be removed from a string
  * @return the string after removing the specified chars
  */
 public static String removeCharsFromString(String aString, char[] unWantedCharArray) {
     Character character = null;
     // Store unwanted chars in a hashset
     Set unWantedCharSet = new HashSet();
     for (int i = 0; i < unWantedCharArray.length; i++) {
         character = new Character(unWantedCharArray[i]);
         unWantedCharSet.add(character);
     }
     // Create result String buffer
     StringBuffer result = new StringBuffer(aString.length());
     // For each character in aString, append it to the result string buffer
     // if it is not in unWantedCharSet
     for (int i = 0; i < aString.length(); i++) {
         character = new Character(aString.charAt(i));
         if (!unWantedCharSet.contains(character)) {
             result.append(aString.charAt(i));
         }
     }
     // Return result
     return result.toString();
 }

}



 </source>
   
  
 
  



Remove whitespace from the ends as well as excessive whitespace within the inside of the string between non-whitespace characters.

   <source lang="java">
 

/*

*  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 {

 /**
  * A deep trim of a string remove whitespace from the ends as well as
  * excessive whitespace within the inside of the string between
  * non-whitespace characters. A deep trim reduces internal whitespace down
  * to a single space to perserve the whitespace separated tokenization order
  * of the String.
  * 
  * @param string
  *            the string to deep trim.
  * @return the trimmed string.
  */
 public static final String deepTrim( String string )
 {
     return deepTrim( string, false );
 }
 /**
  * This does the same thing as a trim but we also lowercase the string while
  * performing the deep trim within the same buffer. This saves us from
  * having to create multiple String and StringBuffer objects and is much
  * more efficient.
  * 
  * @see StringTools#deepTrim( String )
  */
 public static final String deepTrimToLower( String string )
 {
     return deepTrim( string, true );
 }
 /**
  * Put common code to deepTrim(String) and deepTrimToLower here.
  * 
  * @param str
  *            the string to deep trim
  * @param toLowerCase
  *            how to normalize for case: upper or lower
  * @return the deep trimmed string
  * @see StringTools#deepTrim( String )
  * 
  * TODO Replace the toCharArray() by substring manipulations
  */
 public static final String deepTrim( String str, boolean toLowerCase )
 {
     if ( ( null == str ) || ( str.length() == 0 ) )
     {
         return "";
     }
     char ch;
     char[] buf = str.toCharArray();
     char[] newbuf = new char[buf.length];
     boolean wsSeen = false;
     boolean isStart = true;
     int pos = 0;
     for ( int i = 0; i < str.length(); i++ )
     {
         ch = buf[i];
         // filter out all uppercase characters
         if ( toLowerCase )
         {
             if ( Character.isUpperCase( ch ) )
             {
                 ch = Character.toLowerCase( ch );
             }
         }
         // Check to see if we should add space
         if ( Character.isWhitespace( ch ) )
         {
             // If the buffer has had characters added already check last
             // added character. Only append a spc if last character was
             // not whitespace.
             if ( wsSeen )
             {
                 continue;
             }
             else
             {
                 wsSeen = true;
                 if ( isStart )
                 {
                     isStart = false;
                 }
                 else
                 {
                     newbuf[pos++] = ch;
                 }
             }
         }
         else
         {
             // Add all non-whitespace
             wsSeen = false;
             isStart = false;
             newbuf[pos++] = ch;
         }
     }
     return ( pos == 0 ? "" : new String( newbuf, 0, ( wsSeen ? pos - 1 : pos ) ) );
 }

}


 </source>
   
  
 
  



Replace Characters in a String

   <source lang="java">
   

public class Main {

   public static void main(String[] args) {
       String str = "abc";
       
       str = str.replace("b", "d");
       
       System.out.println(str);
   }

} //adc



 </source>
   
  
 
  



Returns a new string with all the whitespace removed

   <source lang="java">
  

import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Map;

/*

 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

public class Main{

 /**
  * Returns a new string with all the whitespace removed
  * 
  * @param s the source string
  * @return the string without whitespace or null
  */
 public static String removeWhiteSpace(String s)
 {
    String retn = null;
    
    if (s != null)
    {
       int len = s.length();
       StringBuffer sbuf = new StringBuffer(len);
       
       for (int i = 0; i < len; i++)
       {
          char c = s.charAt(i);
          
          if (!Character.isWhitespace(c))
              sbuf.append(c);
       }
       retn = sbuf.toString();
    }
    return retn;
 }

}


 </source>
   
  
 
  



StrCharAt - show String.charAt()

   <source lang="java">
   

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/** StrCharAt - show String.charAt()

* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: StrCharAt.java,v 1.3 2004/02/09 03:34:03 ian Exp $
*/

public class StrCharAt {

   public static void main(String[] av) {
       String a = "A quick bronze fox lept a lazy bovine";
   for (int i=0; i < a.length(); i++)
     System.out.println("Char " + i + " is " + a.charAt(i));
 }

}




 </source>
   
  
 
  



The character array based string

   <source lang="java">
  

/*

* 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.
*/

/**

* 
* @author Eric Ye, IBM
* @author Andy Clark, IBM
* 
* @version $Id: XMLString.java 447247 2006-09-18 05:23:52Z mrglavas $
*/

public class XMLString {

 /** The character array. */
 public char[] ch;
 /** The offset into the character array. */
 public int offset;
 /** The length of characters from the offset. */
 public int length;
 //
 // Constructors
 //
 /** Default constructor. */
 public XMLString() {
 } // <init>()
 /**
  * Constructs an XMLString structure preset with the specified values.
  * 
  * @param ch
  *          The character array.
  * @param offset
  *          The offset into the character array.
  * @param length
  *          The length of characters from the offset.
  */
 public XMLString(char[] ch, int offset, int length) {
   setValues(ch, offset, length);
 } // <init>(char[],int,int)
 /**
  * Constructs an XMLString structure with copies of the values in the given
  * structure.
*

* Note: This does not copy the character array; only the * reference to the array is copied. * * @param string * The XMLString to copy. */ public XMLString(XMLString string) { setValues(string); } // <init>(XMLString) // // Public methods // /** * Initializes the contents of the XMLString structure with the specified * values. * * @param ch * The character array. * @param offset * The offset into the character array. * @param length * The length of characters from the offset. */ public void setValues(char[] ch, int offset, int length) { this.ch = ch; this.offset = offset; this.length = length; } // setValues(char[],int,int) /** * Initializes the contents of the XMLString structure with copies of the * given string structure. * <p> * Note: This does not copy the character array; only the * reference to the array is copied. * * @param s */ public void setValues(XMLString s) { setValues(s.ch, s.offset, s.length); } // setValues(XMLString) /** Resets all of the values to their defaults. */ public void clear() { this.ch = null; this.offset = 0; this.length = -1; } // clear() /** * Returns true if the contents of this XMLString structure and the specified * array are equal. * * @param ch * The character array. * @param offset * The offset into the character array. * @param length * The length of characters from the offset. */ public boolean equals(char[] ch, int offset, int length) { if (ch == null) { return false; } if (this.length != length) { return false; } for (int i = 0; i < length; i++) { if (this.ch[this.offset + i] != ch[offset + i]) { return false; } } return true; } // equals(char[],int,int):boolean /** * Returns true if the contents of this XMLString structure and the specified * string are equal. * * @param s * The string to compare. */ public boolean equals(String s) { if (s == null) { return false; } if (length != s.length()) { return false; } // is this faster than call s.toCharArray first and compare the // two arrays directly, which will possibly involve creating a // new char array object. for (int i = 0; i < length; i++) { if (ch[offset + i] != s.charAt(i)) { return false; } } return true; } // equals(String):boolean // // Object methods // /** Returns a string representation of this object. */ public String toString() { return length > 0 ? new String(ch, offset, length) : ""; } // toString():String } // class XMLString </source>

To remove a character

   <source lang="java">
   

public class Main {

 public static void main(String args[]) {
   String str = "this is a test";
   
   System.out.println(removeChar(str,"s"));
 }
 public static String removeChar(String s, char c) {
   String r = "";
   for (int i = 0; i < s.length(); i++) {
     if (s.charAt(i) != c)
       r += s.charAt(i);
   }
   return r;
 }

} //thi i a tet



 </source>