String class java commonly insights

String manipulation is computer programming, the most common behavior, so use a good grasp of the String class is very important.
String is a final modified class, so it is not inherited, String objects are not changed, that creates an object in the future, then the length of this object can not be amended, but we usually conducted string concatenation, modification and other operations are just copies of its references, and does not change the size of the original string.
The following piece of code to understand through a String object is created;

       //创建String对象
        String str="yxc";
        String str2="yxc";
        String str1=new String("yxc");
        String str3=new String("yxc");
        System.out.println(str1==str3);
        System.out.println(str==str2);
        System.out.println(str==str1);

Return result:
false
to true
false
may be a little confusing for beginners, then the following by way of illustration to analyze the (still looking for the right drawing software, temporarily hand animation :)

Here Insert Picture DescriptionFor the first str and str2, it created a constant pool "yxc" constant, and then address it to str, str2.
And str1 and str3, the first to use new keyword to create an object in the heap, and then heap memory reference while passed passed str3 str1 and come back is a reference constant pool.
Look at the following piece of code:

       String str1="hello world";
       String str2=str1.substring(2);
       System.out.println(str2);
       System.out.println(str1);

Operating results:
the LLO world
the Hello world
for the substring function is the interception of a string, followed by the parameter indicates the index where to start capturing, say that we follow here want to say is, we modified by str.substring (), but the original string str1 fact has not changed, this is the string can not become, in fact, this design is exactly what we need, many times we do not want to modify the original value. For function strings are usually successful if the operation returns a new object, if not return to the original subject, so that saves a lot of space, how to say, look at the code below:

       tring str1="hello world";
       String str2=str1.substring(0);
       String str3=str1.substring(1);
       System.out.println(str1==str3);
       System.out.println(str1==str2);

Results are returned:
false
to true
right, which shows the return of the original object and returns a new object. Channeling character in many ways are designed this way, let's learn about String commonly used method. By adding a code to get detailed comments directly:

package com.yxc.string;
//测试String中常见的方法
public class StringProject {
    public static void main(String[] args) {
        System.out.println("其它数据类型转为String类型测试");
       //将其它数据类型转为字符串
        double d=123456.7;
        String str1 = String.valueOf(d);
        System.out.println(str1);   //123456.7
        //其它的数据类型都是一样的,只是换一下数据类型就可以
        //这里还有一种稍微特殊一点的
        char[] c=new char[]{'a','y','z','w'};
        //从下标为1开始截取,截取两个,然后将这两个转换为字符串
        String str2 = String.valueOf(c, 1, 2);
        System.out.println(str2);    //yz


        System.out.println("字符串转为其它数据类型");
        String str3="3121";
        int j = Integer.parseInt(str3);
        System.out.println(j);   //3121
        //其它的数据类型类似

        System.out.println("计算字符串长度");
        System.out.println(str3.length());//注意length是方法,不是数据中的属性

        System.out.println("字符串开头和结尾 返回boolean类型");
        String str4="jamesy";
        System.out.println(str4.startsWith("j"));//true
        System.out.println(str4.endsWith("k"));   //false

        System.out.println("索引");
        /**
         * 索引元素,如果存在返回字符串所在的下标,下标从零开始 如果不存在返回-1
         * 如果是从后面索引,如果找到也是返回下标吗,而是是从前往后的下标(注意)
         * 如果有相同的就返回第一个查找的的
         */
        String str5="I will give you some color to see see";
        System.out.println(str5.indexOf("give"));
        System.out.println(str5.lastIndexOf("give")); //返回结果也是7
        System.out.println(str5.indexOf("see"));           //30
        System.out.println(str5.lastIndexOf("see"));  //34
        //所以索引see的时候肯定是不一样的,从前往后索引和从后索引第一个出现的see的位置不一样

        System.out.println("忽略大小写比较");
        System.out.println("hello".equalsIgnoreCase("HeLLo"));//true

        System.out.println("根据位置索引值");
        System.out.println("asdfg".charAt(3)); //f

        System.out.println("将字符串转为字符数组");
        String str6="just do it";
        char[] chars = str6.toCharArray();
        for(int i=0;i<chars.length;i++){
            System.out.print(chars[i]);
        }

        System.out.println("截取字符串");
        String str7="justsoso";
        String substring = str7.substring(2, 5);  //sts 2截取到5
        System.out.println(substring);

        System.out.println("连接字符串");
        System.out.println("yxc".concat("xin"));

        System.out.println("将字符串转为字节数组");
        String str8="yuio";
        byte[] bytes = str8.getBytes();
        for(int i=0;i<bytes.length;i++){
            System.out.print(bytes[i]+" ");  //121 117 105 111
        }

        System.out.println("是否包含某一个对象");
        String str9="yangxinchun";
        String str10="xin";
        System.out.println(str9.contains(str10));  //true

    }
}

String class is indeed often used, but in some cases it is inefficient to use, look at the following piece of code:

        long startTime = System.currentTimeMillis();
        String str="yxc";
        for(int i=1;i<100000;i++){
            str=str+i;
        }
        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);

On my machine literally ran 40977ms, (I tested at 10 million, came out a few minutes I did not shut down) of 100-this, but even more frightening is the above operation will produce more than 100,000 objects. Such efficiency is too low and consumption of resources, because creating objects is very resource intensive, just to stitching up a character will generate a new object, and this design is clearly not practical, it has strengthened java String class character stitching string class, StringBuffer and StringBuilder, we test the same time:

        long startTime = System.currentTimeMillis();
        String str="yxc";
        StringBuilder str1=new StringBuilder(str);
        for(int i=1;i<100000;i++){
            str1.append(i);
        }
        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);

Took 27ms

        long startTime = System.currentTimeMillis();
        String str="yxc";
        StringBuffer str1=new StringBuffer(str);
        for(int i=1;i<100000;i++){
            str1.append(i);
        }
        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);

Takes 33ms, it can be seen in the string concatenation above, the efficiency of both the increase is not just a couple of notches, while the latter two for StringBuilder efficiency will be a little high, but it is not thread-safe, the Stringbuffer is thread-safe.

 StringBuffer str=new StringBuffer("abcdefg");
        //stringbuffer中常见的方法

        System.out.println("插入一个元素在字符串中");
        StringBuffer str1 = str.insert(2, "poi");
        System.out.println(str1);   //abpoicdefg
        //和String不一样,str的值发生了改变
        System.out.println(str);  //abpoicdefg
        //也就是说两者的对象时一样的
        System.out.println(str==str1);  //true

        System.out.println("字符串的反转");
        System.out.println(str.reverse());   //gfedciopba

        System.out.println("字符串的删除");
        StringBuffer str3 = str.delete(3, 6);
        System.out.println(str3);  //gfeopba

StringBuilder and StringBuffer are the same, and String some basic methods of these two classes there, can be seen as an extension to the String class, but not inherited, because String is a final modified class can not be inherited. Note that the above operation is an object, after modification, the StringBuffer object has been changed.

Published 33 original articles · won praise 37 · views 4397

Guess you like

Origin blog.csdn.net/weixin_42142899/article/details/101899630