String的初步理解

关于String类的定义和使用

1.

        String str1 = new String("hello");
        String str2 = "hello";
        String str3 = "he"+new String("llo");
        String str4 = "he"+"llo";
        char[] array = {'h','e','l','l','o'};
        String str5 = new String(array);

在这里插入图片描述str1在栈中new了一个新的String;
jdk1.6之前,常量池在方法区
jdk1.7之后,常量池在堆里面
str2 “hello”放在常量池中;
str3实际是new了一个“llo”的String,然后将he连接起来;
str4因为前面的常量池中已经有“hello”了,所以直接指向常量池中的地址;
str5创建new了一个String,只不过里面存的是char类型的数组;

2.String中的方法:

  1. public int length()//返回该字符串的长度
 String str = new String("abcdefg");
 int strlength = str.length();//strlength = 7

  1. public char charAt(int index)//求字符串某一位置字符
    提取子串:
    1)public String substring(int beginIndex)//该方法从beginIndex位置起,从当前字符串中取出剩余 的字符作为一个新的字符串返回。
    2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位置起,从当前字 符串中取出到endIndex-1位置的字符作为一个新的字符串返回。
 String str1 = new String("abcdefg");
 String str2 = str1.substring(2);//str2 = "cdefg"
 String str3 = str1.substring(2,5);//str3 = "cde"
  1. public boolean equals(Object anotherObject)//比较当前字符串和参数字符串
 String str1 = new String("abc");
 String str2 = new String("ABC");
 boolean c = str1.equals(str2);//c=false
  1. 字符串中单个字符查找
    1)public int indexOf(int ch/String str)//用于查找当前字符串中字符或子串,返回字符或子串在当前字符串中从左边起首次出现的位置,若没有出现则返回-1。
    2)public int lastIndexOf(int ch/String str)//该方法与第一种类似,区别在于该方法从字符串末尾位置向前查找。
 String str = "I am a good student";
int a = str.indexOf('a');//a = 2
 int b = str.indexOf("good");//b = 7
 int c = str.indexOf("w",2);//c = -1
int d = str.lastIndexOf("a");//d = 5
 int e = str.lastIndexOf("a",3);//e = 2
  1. String[] split(String str)//将str作为分隔符进行字符串分解,分解后的字字符串在字符串数组中返回。
String str = "asd!qwe|zxc#";
String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";
String str3="I am student";
String[] str4=str3.split(" ");//str4[0]="I";str4[1]="am";str4[2]="student";
  1. getChars() 方法从这个字符串中的字符复制到目标字符数组
    //底层调用的System.arraycopy
  2. intern():如果在常量池当中没有字符串的引用,那么就会生成一个在常量池当中的引 用,相反则不生成。
    //本地方法

3.String 和StringBuffer 和StringBuilder 比较

在执行速度上:Stringbuilder->Stringbuffer->String
String是字符串常量
String 类 是不可变类,不能试图去修改它的值
public final class String
final 定义的 一次赋值,不可修改
 Stringbuffer是字符串变量  Stringbuilder是字符串变量
StringBuffer:  synchronized线程安全  多线程
StringBuilder:  单线程

猜你喜欢

转载自blog.csdn.net/qq_39602004/article/details/83412345
今日推荐