String中重要方法与字段

下列这段代码已全部包含了我要写的String类中重要的字段:

 

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

以下是程序运行结果截图:

 Length()的用法::获取字串长度

数组有length属性,字符串有length()方法
所以,字符串长度用length();数组可以用length;

java.lang.String.charAt()  用法:   方法返回指定索引处的char值。索引范围是从0到length() - 1。对于数组索引,序列的第一个char值是在索引为0,索引1,依此类推,返回值为char类型不可以用String类型得到。

getChars()用法:获取从指定位置起的子串复制到字符数组中(它有四个参数)

getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin)将字符从此字符串复制到目标字符数组。 

要复制的第一个字符在索引 srcBegin 处;要复制的最后一个字符在索引 srcEnd-1 处(因此要复制的字符总数是 srcEnd-srcBegin)。要复制到 dst 子数组的字符从索引 dstBegin 处开始,并结束于索引.例如
String str = "abcdefghikl";
Char[] ch = new char[8];
str.getChars(2,5,ch,0);
就是从str的第二个字母开始一直复制到第五个,一共是3个字符,从ch的第一个开始接受.

replace():子串替换用法:

toUpperCase()、 toLowerCase():大小写转换:

toUpperCase()将小写转换为大写,toLowerCase()将大写转换为小写;()内可以是String char类型的变量名也可以是“字符串”。

trim():去除头尾空格:

toCharArray():将字符串对象转换为字符数组

具体用法:

 String myString="abcd";
char myChar[]=myString.toCharArray();
 

 

posted @ 2015-10-22 09:03  码农小正  阅读(349)  评论(0编辑  收藏  举报