Java Tutorial/Data Type/String vs Char Array

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

Checks that the String does not contain certain characters.

/**
 * 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
 * <code>null</code> 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 <code>null</code> String will return <code>true</code>.
   * A <code>null</code> invalid character array will return <code>true</code>.
   * An empty String ("") always returns true.
   *
   * <pre>
   * 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
   * </pre>
   *
   * @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 <code>null</code> String will return <code>true</code>.
   * A <code>null</code> invalid character array will return <code>true</code>.
   * An empty String ("") always returns true.
   *
   * <pre>
   * 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
   * </pre>
   *
   * @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 <code>null</code>.
   *
   * @param array  the array to test
   * @return <code>true</code> if the array is empty or <code>null</code>
   * @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.
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * 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 <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





Checks whether the String contains only digit characters.

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 <code>String</code> contains only
   * digit characters.
   *
   * <code>Null</code> and empty String will return
   * <code>false</code>.
   *
   * @param str  the <code>String</code> to check
   * @return <code>true</code> 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;
  }
}





Construct one String from another.

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);
  }
}





Copy characters from string into char Array

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 );
   }
}



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

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);
  }
}



not


Creating Character Arrays From String Objects

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);
      
    }
  }
}



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


Creating String Objects From Character Arrays

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);
  }
}



To be or not to be


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

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);
  }
}



To be or not to be


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

/*
 * 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)}.
   *
   * <pre>
   * StringUtils.deleteWhitespace(null)         = null
   * StringUtils.deleteWhitespace("")           = ""
   * StringUtils.deleteWhitespace("abc")        = "abc"
   * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
   * </pre>
   *
   * @param str  the String to delete whitespace from, may be null
   * @return the String without whitespaces, <code>null</code> 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.
   *
   * <pre>
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * </pre>
   *
   * 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 <code>true</code> if the String is empty or null
   */
  public static boolean isEmpty(String str) {
      return str == null || str.length() == 0;
  }
}





demonstrates getChars( ):

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);
  }
}





Demonstrates the charAt and getChars

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 );
   }
}



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()

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);
      
    }
  }
}



n
o
t


implements CharSequence

/*******************************************************************************
 * 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);
  }
}





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

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);
  }
}



not


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

/*
 *  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 &lt;= 32) from end of this String, handling
   * <code>null</code> by returning <code>null</code>.
   * 
   * Trim removes start characters &lt;= 32.
   * 
   * <pre>
   *  StringUtils.trimRight(null)          = null
   *  StringUtils.trimRight(&quot;&quot;)            = &quot;&quot;
   *  StringUtils.trimRight(&quot;     &quot;)       = &quot;&quot;
   *  StringUtils.trimRight(&quot;abc&quot;)         = &quot;abc&quot;
   *  StringUtils.trimRight(&quot;    abc    &quot;) = &quot;    abc&quot;
   * </pre>
   * 
   * @param str
   *            the String to be trimmed, may be null
   * @return the trimmed string, <code>null</code> 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 &lt;= 32) from start of this String, handling
   * <code>null</code> by returning <code>null</code>.
   * 
   * Trim removes start characters &lt;= 32.
   * 
   * <pre>
   *  StringUtils.trimLeft(null)          = null
   *  StringUtils.trimLeft(&quot;&quot;)            = &quot;&quot;
   *  StringUtils.trimLeft(&quot;     &quot;)       = &quot;&quot;
   *  StringUtils.trimLeft(&quot;abc&quot;)         = &quot;abc&quot;
   *  StringUtils.trimLeft(&quot;    abc    &quot;) = &quot;abc    &quot;
   * </pre>
   * 
   * @param str
   *            the String to be trimmed, may be null
   * @return the trimmed string, <code>null</code> 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.
   * 
   * 
   * <pre>
   *  StringUtils.isEmpty(null)      = true
   *  StringUtils.isEmpty(&quot;&quot;)        = true
   *  StringUtils.isEmpty(&quot; &quot;)       = false
   *  StringUtils.isEmpty(&quot;bob&quot;)     = false
   *  StringUtils.isEmpty(&quot;  bob  &quot;) = false
   * </pre>
   * 
   * 
   * 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 <code>true</code> if the String is empty or null
   */
  public static final boolean isEmpty( String str )
  {
      return str == null || str.length() == 0;
  }
}





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

/*
 *  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 &lt;= 32) from end of this String, handling
   * <code>null</code> by returning <code>null</code>.
   * 
   * Trim removes start characters &lt;= 32.
   * 
   * <pre>
   *  StringUtils.trimRight(null)          = null
   *  StringUtils.trimRight(&quot;&quot;)            = &quot;&quot;
   *  StringUtils.trimRight(&quot;     &quot;)       = &quot;&quot;
   *  StringUtils.trimRight(&quot;abc&quot;)         = &quot;abc&quot;
   *  StringUtils.trimRight(&quot;    abc    &quot;) = &quot;    abc&quot;
   * </pre>
   * 
   * @param str the String to be trimmed, may be null
   * @param escapedSpace The last escaped space, if any
   * @return the trimmed string, <code>null</code> 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.
   * 
   * 
   * <pre>
   *  StringUtils.isEmpty(null)      = true
   *  StringUtils.isEmpty(&quot;&quot;)        = true
   *  StringUtils.isEmpty(&quot; &quot;)       = false
   *  StringUtils.isEmpty(&quot;bob&quot;)     = false
   *  StringUtils.isEmpty(&quot;  bob  &quot;) = false
   * </pre>
   * 
   * 
   * 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 <code>true</code> if the String is empty or null
   */
  public static final boolean isEmpty( String str )
  {
      return str == null || str.length() == 0;
  }
}





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

/*
 * 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.
   *
   * <ul>
   *  <li>Upper case character converts to Lower case</li>
   *  <li>Title case character converts to Lower case</li>
   *  <li>Lower case character converts to Upper case</li>
   * </ul>
   *
   * For a word based algorithm, see {@link WordUtils#swapCase(String)}.
   * A <code>null</code> input String returns <code>null</code>.
   *
   * <pre>
   * StringUtils.swapCase(null)                 = null
   * StringUtils.swapCase("")                   = ""
   * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
   * </pre>
   *
   * 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, <code>null</code> 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();
  }
}





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

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.");      
  }
}



The phrase contains 12 vowels.