//StringMisc.java

// This program demonstrates the length, charAt and getChars

// methods of the String class.

//

// Note: Method getChars requires a starting point

// and ending point in the String. The starting point is the

// actual subscript from which copying starts. The ending point

// is one past the subscript at which the copying ends.

import javax.swing.*;

 

public class StringMisc {

   public static void main( String args[] )

   {

      String s1, output;

      char charArray[];

 

      s1 = new String( "hello there" );

      charArray = new char[ 5 ];

 

      // output the string

      output = "s1: " + s1;

 

      // test the length method

      output += "\nLength of s1: " + s1.length();

 

      // loop through the characters in s1 and display reversed

      output += "\nThe string reversed is: ";

 

      for ( int i = s1.length() - 1; i >= 0; i-- )

         output += s1.charAt( i ) + " ";

 

      // copy characters from string into char array

      //四个参数的含义

      //1.被拷贝字符在字串中的起始位置

      //2.被拷贝的最后一个字符在字串中的下标再加1

      //3.目标字符数组

      //4.拷贝的字符放在字符数组中的起始下标

      s1.getChars( 0, 5, charArray, 0 );

      output += "\nThe character array is: ";

 

      for ( int i = 0; i < charArray.length;i++ )

         output += charArray[ i ];

 

      JOptionPane.showMessageDialog( null, output,

         "Demonstrating String Class Constructors",

         JOptionPane.INFORMATION_MESSAGE );

 

      System.exit( 0 );

   }

}

}

  1. Length():获取字串长度  《空格也算他的长度》
  2. charAt():获取指定位置的字符
  3. getChars():获取从指定位置起的子串复制到字符数组中(它有四个参数,在示例中有介绍)
  4. replace():子串替换
  5. toUpperCase()、 toLowerCase():大小写转换
  6. trim():去除头尾空格:
  7. toCharArray():将字符串对象转换为字符数组