构造方法:
public class StringTest01 {
public static void main(String[] args) {
byte [] bytes = {97,98,99}; //abc
//String(字节数组,数组元素下标的起始位置,长度)
String s1 = new String(bytes,1,2); //可将byte数组中一部分元素转为字符串
String s2 = new String(bytes); //将byte数组全部转为字符串
System.out.println(s1); //输出bc
System.out.println(s2); //输出abc
char[] chars ={'你','好','啊'};
String s3 = new String(chars);
String s4 = new String(chars,0,1);
System.out.println("s3:"+ s3 + "s4:"+s4);
}
}
方法:
public class StringTest02 {
public static void main(String[] args) {
//1、char charAt(int index)
char c = "中国人".charAt(1);//"中国人"是一个字符串String对象
System.out.println(c); //输出 国
//2、int compareTo(String anotherString) 按字典顺序比较字符串 (这里int是输出结果类型)
//字符串之间比较大小不能直接使用<>,应使用compareTo方法
System.out.println("abc".compareTo("abc")); //输出 0 (前后一致)
System.out.println("abcd".compareTo("abce")); //输出 -1(前小后大)
int result = "abce".compareTo("abcd");
System.out.println(result); //输出 1(前大后小)
//字符相同,顺序不同时,先比较字符串第一个字母,若可比较出来,则结束,若第一个字母相等,则顺延后面字母进行比较
System.out.println("abc".compareTo("acb"));//输出-1
//3、boolean contains(CharSequence s)
//判断前面字符串中是否包含后面子字符串
System.out.println("hello.java".contains("java"));//输出true
System.out.println("http://dadsadasd".contains("https://"));//输出false
//4、boolean endsWith(String suffix)
//判断当前字符串是否以某个字符串结尾
System.out.println("hello.java".endsWith(".java")); //输出true
System.out.println("dwswadqdwsa".endsWith("wsa")); //输出true
//5、boolean equalsIgnoreCase(String anotherString)
//判断两个字符串是否相等,并且同时忽略大小写
System.out.println("ABc".equalsIgnoreCase("abc"));//输出true
//6、byte[] getBytes()
//将字符串对象转换为字节数组
byte[] bytes = "abcde".getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);//输出97 98 99 100 101
}
//7、int indexOf(String str) 判断某个子字符串在当前字符串中第一次出现处的下标
// int lastIndexOf(String str)判断某个子字符串在当前字符串中最后一次出现处的下标
System.out.println("waijavabutjavadontloveme".indexOf("java"));//输出3
//8、boolean isEmpty()
//判断某个字符串是否为空字符串
String s = "";
System.out.println(s.isEmpty()); //输出true
//9、int length()
//注意⚠️:判断数组长度和判断字符串长度不同
//判断数组长度是length属性,判断字符串长度是length()方法
System.out.println("abc".length());//输出3
//10、String replace(target,replacement)
//替换
String newString = "http://www.java.com".replace("http://","https://");
System.out.println(newString);//输出https://www.java.com
String newString1 = "12=23=12=321=4".replace("=",":");//将=全部替换为:
System.out.println(newString1);//输出12:23:12:321:4
//11、String[] split(String regex)
//拆分字符串
String[] spl = "123-22-13".split("-");//以"-"进行拆分
for (int i = 0; i < spl.length; i++) {
System.out.println(spl[i]);//输出123 22 13
}
String all = "1=2=3=4";
String[] alls = all.split("=");
for (int i = 0; i < alls.length; i++) {
System.out.println(alls[i]);
}
//更多String方法见API帮助文档
}
}



