String类:
String代表字符串类,java中所有双引号中的内容都称为字符串,如:“hello”。字符串是不可改变的,因此字符串是可以共享使用的,相当于char字符数组,但是底层原理是byte字节数组。
创建字符串的四种方式:
public class Stringobj{
public static void main(String[] args){
String str1 =new String();
System.out.println(str1);
char[] char1 = {'o','k'};
String str2 = new String(char1);
System.out.println(str2);
byte[] byte1 = {97,98,99};
String str3 = new String(byte1);
System.out.println(str3);
String str4 = "hello,my name is kuhai.";
System.out.println(str4);
}
}
字符串的常量池: 字符串中直接使用双引号包裹的字符串就在常量池中,字符串常量池存在于堆当中,常量池中的字符串可以共享。
public class StringPool{
public static void main(String[] args){
String str1 = "123";
String str2 = "123";
char[] chararr = {'1','2','3'};
String str3 = new String(chararr);
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str2 == str3);
}
}
String类的常用方法:
public class StringMethods{
public static void main(String[] args){
String str1 = "123";
String str2 = "123";
char[] arr = {'1','2','3'};
String str3 = new String(arr);
String str4 = "kuhai";
Boolean str1and2 = str1.equals(str2);
Boolean str1and3 = str1.equals(str3);
Boolean str2and3 = str2.equals(str3);
Boolean str2and4 = str2.equals(str4);
System.out.println(str1and2);
System.out.println(str1and3);
System.out.println(str2and3);
System.out.println(str2and4);
String strabc = "abc";
String strABC = "ABC";
Boolean result1 = strabc.equals(strABC);
Boolean result2 = strabc.equalsIgnoreCase(strABC);
System.out.println(result1);
System.out.println(result2);
System.out.println(str1.length());
String hw = "hello".concat(" world");
System.out.println(hw);
String sayhello = "hello,my name is kuhi!";
char chars = sayhello.charAt(4);
System.out.println(chars);
String hel = "hello";
int indexhel = hel.indexOf("l");
System.out.println(indexhel);
String numstr = "12345";
String substr = numstr.substring(1,3);
System.out.println(substr);
String strtest1 = "abcd";
char[] arrtochararr = strtest1.toCharArray();
System.out.println(arrtochararr[1]);
byte[] bt = "abc".getBytes();
System.out.println(bt[0]);
String says = "你好";
String replacestr = says.replace("你","他");
System.out.println(replacestr);
String names = "jack,李明,韩梅梅";
String[] namearr = names.split(",");
System.out.println(namearr[1]);
}
}
提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:810665436@qq.com联系笔者删除。 笔者:苦海
|