Java Tutorial/Data Type/String vs Char Array

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

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">

import java.math.BigDecimal; import java.math.BigInteger; /**

* 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 
* @author Eric Pugh
* @author Phil Steitz
* @since 1.0
* @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z 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 ((str == null) || (str.length() == 0)) {
         return false;
     }
     for (int i = 0; i < str.length(); i++) {
         if (!Character.isDigit(str.charAt(i))) {
             return false;
         }
     }
     return true;
 }

}</source>





Construct one String from another.

   <source lang="java">

class MakeString {

 public static void main(String args[]) {
   char c[] = { "J", "a", "v", "a" };
   String s1 = new String(c);
   String s2 = new String(s1);
   System.out.println(s1);
   System.out.println(s2);
 }

}</source>





Copy characters from string into char Array

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  {
     String s1 = "hello there";
     char charArray[] = new char[ 5 ];
     System.out.printf( "s1: %s", s1 );
     for ( int count = s1.length() - 1; count >= 0; count-- )
        System.out.printf( "%s ", s1.charAt( count ) );
     // copy characters from string into charArray
     s1.getChars( 0, 5, charArray, 0 );
     System.out.print( "\nThe character array is: " );
     for ( char character : charArray )
        System.out.print( character );
  }

}</source>



s1: hello theree r e h t   o l l e h 
The character array is: hello


Creating a string from a subset of the array elements

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   char[] textArray = { "T", "o", " ", "b", "e", " ", "o", "r", " ", "n", "o", "t", " ", "t", "o",
       " ", "b", "e" };
   String text = String.copyValueOf(textArray, 9, 3);
   
   System.out.println(text);
 }

}</source>



not


Creating Character Arrays From String Objects

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   String text = "To be or not to be";
   char[] textArray = text.toCharArray();
   for(char ch: textArray){
     System.out.println(ch);
     
   }
 }

}</source>



T
o
 
b
e
 
o
r
 
n
o
t
 
t
o
 
b
e


Creating String Objects From Character Arrays

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   char[] textArray = { "T", "o", " ", "b", "e", " ", "o", "r", " ", "n", "o", "t", " ", "t", "o",
       " ", "b", "e" };
   String text = new String(textArray);
   
   System.out.println(text);
 }

}</source>



To be or not to be


Creating String Objects From Character Arrays using String.copyValueOf()

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   char[] textArray = { "T", "o", " ", "b", "e", " ", "o", "r", " ", "n", "o", "t", " ", "t", "o",
       " ", "b", "e" };
   String text = String.copyValueOf(textArray);
   System.out.println(text);
 }

}</source>



To be or not to be


Deletes all whitespaces from a String as defined by Character.isWhitespace(char).

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

 /**
  * Deletes all whitespaces from a String as defined by
  * {@link Character#isWhitespace(char)}.
  *
*
   * StringUtils.deleteWhitespace(null)         = null
   * StringUtils.deleteWhitespace("")           = ""
   * StringUtils.deleteWhitespace("abc")        = "abc"
   * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
   * 
  *
  * @param str  the String to delete whitespace from, may be null
  * @return the String without whitespaces, null if null String input
  */
 public static String deleteWhitespace(String str) {
     if (isEmpty(str)) {
         return str;
     }
     int sz = str.length();
     char[] chs = new char[sz];
     int count = 0;
     for (int i = 0; i < sz; i++) {
         if (!Character.isWhitespace(str.charAt(i))) {
             chs[count++] = str.charAt(i);
         }
     }
     if (count == sz) {
         return str;
     }
     return new String(chs, 0, count);
 }
 // 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>





demonstrates getChars( ):

   <source lang="java">

class getCharsDemo {

 public static void main(String args[]) {
   String s = "This is a demo of the getChars method.";
   int start = 10;
   int end = 14;
   char buf[] = new char[end - start];
   s.getChars(start, end, buf, 0);
   System.out.println(buf);
 }

}</source>





Demonstrates the charAt and getChars

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  {
     String s1 = "hello there";
     char charArray[] = new char[ 5 ];
     System.out.printf( "s1: %s", s1 );
     for ( int count = s1.length() - 1; count >= 0; count-- )
        System.out.printf( "%s ", s1.charAt( count ) );
     // copy characters from string into charArray
     s1.getChars( 0, 5, charArray, 0 );
     System.out.print( "\nThe character array is: " );
     for ( char character : charArray )
        System.out.print( character );
  }

}</source>



s1: hello theree r e h t   o l l e h 
The character array is: hello


Extracting a substring as an array of characters using the method getChars()

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   String text = "To be or not to be";
   char[] textArray = new char[3];
   text.getChars(9, 12, textArray, 0);
   for(char ch: textArray){
     System.out.println(ch);
     
   }
 }

}</source>



n
o
t


implements CharSequence

   <source lang="java">

/*******************************************************************************

* Copyright (c) 2008 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/

/**

* {@link CharSequence} implementation backing by the char[]
*/

public class CharArraySequence implements CharSequence {

 private final char[] buff;
 private final int offset;
 private final int count;
 /**
  * @param buff
  */
 public CharArraySequence(char[] buff) {
   this(buff, 0, buff.length);
 }
 /**
  * @param buff
  * @param count
  */
 public CharArraySequence(char[] buff, int count) {
   this(buff, 0, count);
 }
 /**
  * @param buff
  * @param offset
  * @param count
  */
 public CharArraySequence(char[] buff, int offset, int count) {
   this.buff = buff;
   this.offset = offset;
   this.count = count;
 }
 /*
  * @see java.lang.CharSequence#charAt(int)
  */
 public char charAt(int index) {
   if (index < 0 || index >= count) {
     throw new StringIndexOutOfBoundsException(index);
   }
   return buff[offset + index];
 }
 /*
  * @see java.lang.CharSequence#length()
  */
 public int length() {
   return count;
 }
 /*
  * @see java.lang.CharSequence#subSequence(int, int)
  */
 public CharSequence subSequence(int beginIndex, int endIndex) {
   if (beginIndex < 0) {
     throw new StringIndexOutOfBoundsException(beginIndex);
   }
   if (endIndex > count) {
     throw new StringIndexOutOfBoundsException(endIndex);
   }
   if (beginIndex > endIndex) {
     throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
   }
   return ((beginIndex == 0) && (endIndex == count)) ? this
       : new CharArraySequence(buff, offset + beginIndex, endIndex
           - beginIndex);
 }
 public String toString() {
   return new String(this.buff, this.offset, this.count);
 }

}</source>





new String(textArray, 9, 3): Creating String Objects From certain part of a character Array

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   char[] textArray = { "T", "o", " ", "b", "e", " ", "o", "r", " ", "n", "o", "t", " ", "t", "o",
       " ", "b", "e" };
   String text = new String(textArray, 9, 3);
   
   System.out.println(text);
 }

}</source>



not


Removes spaces (char <= 32) from end of this String, handling null by returning null

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

 /**
  * 
  * Removes spaces (char <= 32) from end of this String, handling
  * null by returning null.
  * 
  * Trim removes start characters <= 32.
  * 
*
   *  StringUtils.trimRight(null)          = null
   *  StringUtils.trimRight("")            = ""
   *  StringUtils.trimRight("     ")       = ""
   *  StringUtils.trimRight("abc")         = "abc"
   *  StringUtils.trimRight("    abc    ") = "    abc"
   * 
  * 
  * @param str
  *            the String to be trimmed, may be null
  * @return the trimmed string, null if null String input
  */
 public static final String trimRight( String str )
 {
     if ( isEmpty( str ) )
     {
         return "";
     }
     int length = str.length();
     int end = length;
     
     while ( ( end > 0 ) && ( str.charAt( end - 1 ) == " " ) )
     {
         if ( ( end > 1 ) && ( str.charAt(  end - 2 ) == "\\" ) )
         {
             break;
         }
         
         end--;
     }
     return ( end == length ? str : str.substring( 0, end ) );
 }
 /**
  * 
  * Removes spaces (char <= 32) from start of this String, handling
  * null by returning null.
  * 
  * Trim removes start characters <= 32.
  * 
*
   *  StringUtils.trimLeft(null)          = null
   *  StringUtils.trimLeft("")            = ""
   *  StringUtils.trimLeft("     ")       = ""
   *  StringUtils.trimLeft("abc")         = "abc"
   *  StringUtils.trimLeft("    abc    ") = "abc    "
   * 
  * 
  * @param str
  *            the String to be trimmed, may be null
  * @return the trimmed string, null if null String input
  */
 public static final String trimLeft( String str )
 {
     if ( isEmpty( str ) )
     {
         return "";
     }
     int start = 0;
     int end = str.length();
     
     while ( ( start < end ) && ( str.charAt( start ) == " " ) )
     {
         start++;
     }
     return ( start == 0 ? str : str.substring( start ) );
 }
 /**
  * 
  * 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 final boolean isEmpty( String str )
 {
     return str == null || str.length() == 0;
 }

}</source>





Removes spaces (char <= 32) from end of this String with escape, handling null by returning null

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

 /**
  * 
  * Removes spaces (char <= 32) from end of this String, handling
  * null by returning null.
  * 
  * Trim removes start characters <= 32.
  * 
*
   *  StringUtils.trimRight(null)          = null
   *  StringUtils.trimRight("")            = ""
   *  StringUtils.trimRight("     ")       = ""
   *  StringUtils.trimRight("abc")         = "abc"
   *  StringUtils.trimRight("    abc    ") = "    abc"
   * 
  * 
  * @param str the String to be trimmed, may be null
  * @param escapedSpace The last escaped space, if any
  * @return the trimmed string, null if null String input
  */
 public static final String trimRight( String str, int escapedSpace )
 {
     if ( isEmpty( str ) )
     {
         return "";
     }
     int length = str.length();
     int end = length;
     
     while ( ( end > 0 ) && ( str.charAt( end - 1 ) == " " ) && ( end > escapedSpace ) )
     {
         if ( ( end > 1 ) && ( str.charAt(  end - 2 ) == "\\" ) )
         {
             break;
         }
         
         end--;
     }
     return ( end == length ? str : str.substring( 0, end ) );
 }
 /**
  * 
  * 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 final boolean isEmpty( String str )
 {
     return str == null || str.length() == 0;
 }

}</source>





Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.

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

 /**
  * Swaps the case of a String changing upper and title case to
  * lower case, and lower case to upper case.
  *
*
    *
  • Upper case character converts to Lower case
  • *
  • Title case character converts to Lower case
  • *
  • Lower case character converts to Upper case
  • *
  *
  * For a word based algorithm, see {@link WordUtils#swapCase(String)}.
  * A null input String returns null.
  *
*
   * StringUtils.swapCase(null)                 = null
   * StringUtils.swapCase("")                   = ""
   * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer performs a word based algorithm.
  * If you only use ASCII, you will notice no change.
  * That functionality is available in WordUtils.
  *
  * @param str  the String to swap case, may be null
  * @return the changed String, null if null String input
  */
 public static String swapCase(String str) {
     int strLen;
     if (str == null || (strLen = str.length()) == 0) {
         return str;
     }
     StringBuffer buffer = new StringBuffer(strLen);
     char ch = 0;
     for (int i = 0; i < strLen; i++) {
         ch = str.charAt(i);
         if (Character.isUpperCase(ch)) {
             ch = Character.toLowerCase(ch);
         } else if (Character.isTitleCase(ch)) {
             ch = Character.toLowerCase(ch);
         } else if (Character.isLowerCase(ch)) {
             ch = Character.toUpperCase(ch);
         }
         buffer.append(ch);
     }
     return buffer.toString();
 }

}</source>





Using the Collection-Based for Loop with a String: Counting all vowels in a string

   <source lang="java">

public class MainClass {

 public static void main(String[] arg) {
   String phrase = "The quick brown fox jumped over the lazy dog.";
   int vowels = 0;
   for(char ch : phrase.toCharArray()) {
     ch = Character.toLowerCase(ch);
     if(ch == "a" || ch == "e" || ch == "i" || ch == "o" || ch == "u") {
       ++vowels;
     }
   }
   System.out.println("The phrase contains " + vowels + " vowels.");      
 }

}</source>



The phrase contains 12 vowels.