String String, StringBuffer and StringBuilder Summary

String
First, let's introduce the storage of
strings. The addition of strings is implemented by append() and toString() of the StringBuffer class, and the string returned by toString() is created by the constructor

Emphasis: The addition of two string constants is changed to a string constant between compilation time.
The addition of string references is to call append() and toString() of the StringBuffer class, which will be created in the heap at this time a new object.

When comparing objects, == and euqals compare the memory address of the object.
For other object classes, hascode defaults to the memory address and equals judges the address.

However, the String class rewrites equals and hascode. As long as the values ​​are the same, the hascode is the same to compare whether the contents of the two string objects are consistent
, so generally equals is used to compare whether the strings are equal.

Note : Understand that String inherits Comparable and rewrites compareTo (compareTo), which is mainly used in the collection to judge the size

Programming habit constants call equals method such as: "sdf".equals(str); because if the caller is empty, an exception will be thrown

String name1="hello"; 
String name2=new String(“hello”);

When creating a string, the jvm will check whether the string constant pool has a "hello" string.
If it exists, it will not create a string object in it. If
it is the first one, it will return the address of the string constant pool.
The second one will copy a copy of the object content of the
string constant pool to the heap memory. There can only be one object in the string
constant pool , and there can be multiple objects in the heap memory with different addresses. The
string constant pool is
named 1 in the method area. If the reference is in stack memory and new in
object memory
Example:

String str1 = "hello";
    String str2 = "hello";
    String str3 = new String("hello");
    String str4 = new String("hello");
    System.out.println("str1==str2?"+(str1==str2));  // true  
    System.out.println("str2==str3?"+(str2==str3));  //false
    System.out.println("str3==str4?"+(str3==str4));  // false
    System.out.println("str3.equals(str2)?"+(str3.equals(str4))); //true

String to determine whether the content is equal

   public static void test(String str){
            if("中国".equals(str))
            {
                System.out.println("回答正确");
            }else{
                System.out.println("回答错误");
            }
        }

String construction

public static void main(String[] args) {

    String name=new String();  //空内容 
    byte[] buf= {97,98,99}; 
    name=new String(buf,0,2);   //0是索引 2是个数  输出ab
    char[] arr= {'我','爱','你'};
    name=new String(arr,0,2);      //同理byte 输出我爱
    int[] buf2= {97,98,99};
    name=new String(buf,0,2);   //同类byte 输出ab
    name=new String("wocainima00"); //输出wocainima00 
    name="xxx";           //输出xxx     
    System.out.print(name);    
}

String get length, position or get string:
int length() get the length of the string
char charAt(int index) get the character at a specific position (the angle mark is out of bounds)
int indexOf(String str) find the first occurrence of the substring The index value, if the substring does not appear in the string, then -1 is returned.
int lastIndexOf(String str) finds the index value of the last occurrence of the substring, and returns -1 if the substring does not appear in the string

Judgment of strings:
byte arrays, character arrays, and strings can be converted to each other.

public static void main(String[] args) {
        String str = "Demo.java";
        System.out.println("是否以指定 的字符串结束:"+ str.endsWith("ja"));
        //str = "";
        System.out.println("判断字符串是否为空内容:"+str.isEmpty());
        System.out.println("判断字符串是否包含指定的内容:"+ str.contains("Demo"));
        System.out.println("判断两个 字符串的内容是否一致:"+ "DEMO.JAVA".equals(str));
        System.out.println("判断两个字符串的内容是否一致(忽略大小写比较):"+ "DEMO.JAVA".equalsIgnoreCase(str));

// method of conversion

char[] buf = str.toCharArray();  //把字符串转换字符数组
        System.out.println("字符数组:"+ Arrays.toString(buf));
        byte[] buf2 = str.getBytes();   //把字符串转字节数组
        System.out.println("字节数组:"+ Arrays.toString(buf2));
    }

String manipulation

String str = "今天晚上不考试";
System.out.println("指定新内容替换旧 的内容:"+ str.replace("不", "要好好"));
        str = "大家-下-午-好";
        String[] arr = str.split("-"); //根据指定的字符进行切割 。
        System.out.println("字符串数组的内容:"+ Arrays.toString(arr));
        str = "广州传智播客";
        System.out.println("指定开始的索引值截取子串:"+ str.substring(2));
        System.out.println("指定开始的索引值截取子串:"+ str.substring(2,6)); //包头不包尾  注意:截取的内容是包括开始的索引值,不包括结束的索引值, 截取的位置是结束的索引值-1.

str = "abC中国";
System.out.println("转大写:" + str.toUpperCase());
str = "AbdfSDD"; 
System.out.println("转小写:"+ str.toLowerCase());

str = "         大家最近        都非常努力            ";
System.out.println("去除字符串首尾的空格:"+ str.trim());

Use of strings:

package cn.itcsat.string;
/*
需求1:自己实现trim的方法。

需求2: 获取上传文件名  "D:\\20120512\\day12\\Demo1.java"。

需求3:    将字符串对象中存储的字符反序。    新中国好     -----> 好国中新

需求4: 求一个子串在整串中出现的次数 。 

public class Demo6 {
    public static void main(String[] args) {
        String str  ="        大家       好嘛             ";    
        System.out.println(myTrim(str));

        str =  "D:\\20120512\\day12\\Demo1.java";
        getFileName(str);

        str = "新中国好";
        System.out.println("翻转后的字符串:"+ reverse(str));

        str = "abcjavaabcjavaphpjava";  //java
        getCount(str, "java");

    }


    //  需求1:自己实现trim的方法。
        public static String myTrim(String str){
            //先转换成字符 数组
            char[] arr = str.toCharArray();
            //定义两个 变量记录开始与结束 的索引值
            int startIndex = 0 ;
            int endIndex = arr.length -1;
            //确定开始 的索引值
            while(true){
                if(arr[startIndex]==' '){
                    startIndex++;
                }else{
                    break;
                }
            }
            //确定结束 的索引值:
            while(true){
                if(arr[endIndex]==' '){
                    endIndex--;
                }else{
                    break;
                }
            }
            //截取子串返回
            return str.substring(startIndex,endIndex+1);        
        }


}

    //需求2: 获取上传文件名  "D:\\20120512\\day12\\Demo1.java"。
    public static void getFileName(String path){
        int index = path.lastIndexOf("\\");
        String fileName = path.substring(index+1);
        System.out.println("文件名:"+ fileName);
    }
        //反转
    public static String reverse(String str){
        char[] arr = str.toCharArray();
        for(int startIndex = 0 , endIndex=arr.length-1 ; startIndex<endIndex; startIndex++,endIndex--){
                char temp = arr[startIndex];
                arr[startIndex] = arr[endIndex];
                arr[endIndex] = temp;
        }
        //使用字符数组构建一个字符串。
        return new String(arr);
    }
    //统计子串出现 的次数
    public static void getCount(String str,String target){
        int count = 0 ; //用于记录出现的次数
        int fromIndex  = 0; // 记录从那个索引值开始寻找目标子串
        while((fromIndex = str.indexOf(target, fromIndex))!=-1){
            //如果indexof方法返回 的不是-1,那么就是已经找到了目标 元素。
            count++;
            fromIndex = fromIndex+target.length();
        }
        System.out.println("出现的次数:"+ count);
    }

There is also a StringBuffer
for strings. If you need to modify the content of the string frequently, it is recommended to use the StringBuffer class.

Written test question: What is the default initial capacity when an object is created using the no-argument constructor of Stringbuffer? If the length is not enough, how many times will it automatically increase?
The bottom layer of StringBuffer relies on a character array to store character data. The default initial capacity of the string array is 16. If the length of the character array is not enough, it will automatically double.

The behavior of the container: increase, delete, modify, view and judge

//先使用StringBuffer无参的构造函数创建一个字符串缓冲类。
            StringBuffer sb = new StringBuffer(); 
            sb.append("java");
            sb.append("java");
            sb.append("java");
            sb.append("java");
            sb.append("java");
    StringBuffer对象和String对象之间的互转的代码如下:
             String s = “abc”;
             StringBuffer sb1 = new StringBuffer(“123”);
             StringBuffer sb2 = new StringBuffer(s);   //String转换为StringBuffer
             String s1 = sb1.toString();              //StringBuffer转换为String

There is no performance loss to splicing strings with a plus sign on a single line. The java compiler will implicitly replace it with stringbuilder,
but in the case of loops, the compiler cannot do smart enough replacement, and there will still be unnecessary performance. Loss,
therefore, when using loops to concatenate strings, use stringbuilder honestly.

The difference between String, StringBuffer and StringBuilder??

Notice:

1. String objects of type String are immutable. Once the String object is created, the character series contained in the object cannot be changed until the object is destroyed.

2. Strings of StringBuilder and StringBuffer types are mutable. The difference is that StringBuffer types are thread-safe, while StringBuilder is not thread-safe.

3. If it involves the insertion and deletion of shared variables in a multi-threaded environment, StringBuffer is the first choice. StringBuilder is the first choice if it is a non-multithreaded operation and has a large number of string concatenation, insertion, deletion operations. After all, the String class implements string splicing by creating temporary variables, which consumes memory and is not efficient. How to say StringBuilder realizes the ultimate operation through JNI.

4. The "mutable" features of StringBuilder and StringBuffer are summarized as follows:

(1) The append, insert, delete methods basically call the System.arraycopy() method to achieve their goals


(2) The substring(int, int) method achieves its purpose by renewing the new String(value, start, end - start). So there is basically no difference between StringBuilder and String when performing substring operations.

When using a single thread, it is basically correct to use StringBuild. There are mainly methods such as append and insert.

StringBuffer method
//First create a string buffer class using StringBuffer's no-argument constructor.
StringBuffer sb = new StringBuffer();
sb.append("abcjavaabc");
/*
add
sb.append(true);
sb.append(3.14f);
insert

    sb.insert(2, "小明");
    */

    /*
    删除
    sb.delete(2, 4); //  删除的时候也是包头不包尾
    sb.deleteCharAt(3); //根据指定 的索引值删除一个字符

    修改  
    sb.replace(2, 4, "陈小狗");

    sb.reverse(); // 翻转字符串的内容

    sb.setCharAt(3, '红');

    String subString = sb.substring(2, 4);
    System.out.println("子串的内容:"+ subString);

    查看

    int index = sb.indexOf("abc", 3);
    System.out.println("索引值为:"+index);

    sb.append("javajava");
    System.out.println("查看字符数组的长度:"+ sb.capacity());
    */

    System.out.println("存储的字符个数:"+sb.length());
    System.out.println("索引指定的索引值查找字符:"+sb.charAt(2) );
    System.out.println("字符串缓冲类的内容:"+ sb);

    String content = sb.toString();
    test(content);
String s1 = "abc";

String s2 = "a";

String s3 = "bc";

String s4 = s2 + s3;

System.out.println(s1 == s4);

结果为: false

原理是: 字符串相加是通过StringBuffer类的append()和toString()实现的, 而toString()返回的字符串是通过构造函数创建的.

toString() is converted to String type
. If it is a reference object, the value is the full class name@address.
If it is String, it is the output result
and System.out.println will automatically call toString()
StringBuilder can add strings without creating new characters The string toString returns is that the string is new in the heap

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326006835&siteId=291194637