String类的方法

String 

(1)String类的对象,其长度就不可再改变,其任何一个字符能修,因此称String类的对象是不可变的。

(2)String类的方法,使用了字符索引的概念来处理字符串。一个字符可以由该字符在字符串中的位置(索引)来决定。字符串中第一个字符的索引为0,下一个字符的索引为1,以此类推。例如:在字符串“Hello”中,‘H’的索引是0,‘o’的索引是4

String 类的方法

1String(String str) 

     // 构造方法,建立一个新的String对象,并用参数str字符串进行对象的初始化。

(2)char charAt(int index)

     // 返回指定索引位置的字符

(3)int compareTo(String str) 

     // 返回一个整型数,正值,0,负值;表示本对象的字符串按照字典顺序位置先于,等于或后于str对象的字符串的字母个数

(4)String concat(String str)

     // 返回一个由本对象字符串与str对象字符串拼接后的新串对象。

(5)boolean equals(String str)

     // 如果本对象字符串与str对象字符串相同(区分大小),返回真,反之,返回假。

(6)boolean equalsIgnoreCase(String str)

     // 如果本对象字符串与str对象字符串相同(不区分大小写),......................................

(7)int length()

     // 返回本对象字符串所包含的字符个数

(8)String replace(char oldChar, char new Char)

     // 将本对象字符串中所有形如oldChar的子串用新子串newChar替换后,构成新字符串对象返回。

(9)String substring(int offset, int endIndex)

     // 从本对象字符串中的offset位置开始到endIndex-1位置,取一个子串构成新字符串对象返回。

(10)String toLowerCase()

     // 将本对象字符串的所有大写字母转换为小写字母,构成新字符串对象返回。

(11)String toUpperCase()

1String类的方法

public class StringMutation1 {

public static void main(String arge[])

{

String str = "Change is inevitable";

System.out.println("Original string: "+str);

System.out.println("Length of string: "+str.length());

 

String str1,str2,str3,str4;

str1 = str.concat(",except from vending machines.");

System.out.println("Mutation #1: "+str1);

str2 = str1.toUpperCase();

System.out.println("Mutation #2: "+str2);

str3 = str2.replace('E''X');

System.out.println("Mutation #3: "+str3);

str4 = str3.substring(3,20);

System.out.println("Mutation #4: "+str4);

 

int cmp1,cmp2,cmp3;

cmp1 = str.compareTo("Change is available");

cmp2 = str.compareTo("Change was inevitable");

cmp3 = str.compareTo("Change is inevitable");

    System.out.println("\nthe first compare is: "+cmp1+"\n"

                 +"the second compare is: "+cmp2+"\n"

                 +"the third  compare is: "+cmp3);

    

    char ch1,ch2;

    ch1 = str.charAt(0);

    ch2 = str.charAt(2);

    System.out.println("\n返回的第0个位置上的字符为:"+ch1

                +"\n返回的第2个位置上的字符为:"+ch2);

    

    String str5,str6;

    str5 = "Change is inevitable";

    str6 = "CHANGE is INEVITABLE";

    System.out.println("\n strstr5相同吗?"+str.equals(str5)

               + "\n strstr6相同吗?"+str.equals(str6)

       + "\n strstr6相同吗?(不考虑大小写时)"+str.equalsIgnoreCase(str6));

    }

}

 

输出结果:

Original string: Change is inevitable

Length of string: 20

Mutation #1: Change is inevitable,except from vending machines.

Mutation #2: CHANGE IS INEVITABLE,EXCEPT FROM VENDING MACHINES.

Mutation #3: CHANGX IS INXVITABLX,XXCXPT FROM VXNDING MACHINXS.

Mutation #4: NGX IS INXVITABLX

 

the first compare is: 8

the second compare is: -14

the third compare is: 0

 

返回的第0个位置上的字符为:C

返回的第2个位置上的字符为:a

 

 strstr5相同吗?true

 strstr6相同吗?false

 strstr6相同吗?(不考虑大小写时)true

posted @ 2013-10-18 15:20  seven_wang  阅读(227)  评论(0编辑  收藏  举报