关于String类的连续调用启发,以及String类函数方法总结

动手动脑一:

String类的方法可以连续调用:

String str="abc";

String result=str.trim().toUpperCase().concat("defg");

请阅读JDK中String类上述方法的源码,模仿其编程方式,编写一个MyCounter类,它的方法也支持上述的“级联”调用特性,其调用示例为:

MyCounter counter1=new MyCounter(1);

MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

(一)源代码:

 

public class MyCounter {

 

    int counter=0;

    public MyCounter(int i) {

        counter=i;

    }

    public  MyCounter increase(int add) {

        counter=counter+add;

        return this;

    }

    public MyCounter decrease(int minus) {

        counter=counter-minus;

        return this;

    }

   

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        MyCounter counter1=new MyCounter(1);

        MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

        System.out.println("计算结果为:"+counter2.counter);

 

    }

 

}

(二)程序结果截图:

 

 

(三)原因分析:

(1)构造函数:

<类名><函数名>(参数列表){

函数体;

return this;}

这样声明是为了能够连续调用类中的函数,return this就是返回当前这个类的当前的对象,方便构造函数相互调用,可用于连续调用中。

 

动手动脑二:

String.equals()方法、整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明。

(1)String.equals()方法与String.equalsIgnoreCase()方法比较:

String.equals()用于比较两个字符串的内容是否相同,而另一个比较相等的“==”符号则是比较是否引用同一对象。举例如下:

 

其中对象s1赋给对象s2,是引用同一个对象,也就相当于指向同一个地址。因为String类是字符串管理者而非所有者,若为赋值,则指向同一个地址;若为比较,则比较是否在同一个地址。因此“s1==s2”//true。当s1+=”b”;后s1=”ab”,与s2不相等,代码中的“ab”字符串是一个常量,它所引用的字符串与s1所引用的“ab”对象无关。所以s1==”ab”;//false但是内容相同所以s1.equals(“ab”);//true。

String.equalsIgnoreCase()同样用于比较字符串的内容,但是equals考虑大小写,equalsIgnoreCase忽略大小写。

(2)下面总结了一些关于String类的函数用法:

String.Length():显示字符串的长度,包含空格。

String.charAt():查找字符串某一位的字符。比如String  s1=”Hello”;那么s1.charAt(1)则为‘e’。

String.getChars():获取从指定位置起的子串复制到字符数组中

String.replace():子串替换

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

String.trim():去除头尾空格

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

String.startsWith():查找字符串是否以某个字符开头,返回true或false。

String.endWith():查找字符串是否以某个字符结尾,返回true或false。

String.indexOf():在字符串查找字符或字串;”String.indexOf( 'a', n );”//从第n+1个参数开始查找‘a’;”String.lastIndexOf()”查找字符串中最后一个此字符或字串的位置;若查找到,则返回字符串位置号,没有查找到则返回-1。

 

 

 

 

 

 

posted @ 2017-10-26 15:53  Someday&Li  阅读(546)  评论(0编辑  收藏  举报