1.对字符串的理解及四种创建方法
字符串的构造方法:
//public String()使用空参构造
String str1=new String();//构造了一个空字符串
//public String(char[] array)使用字符数组构造字符串
char[] charArray= {'A','B','C'};
String str2=new String(charArray);
//public String(byte[] array)使用字符数组构造字符串
byte[] byteArray= {97,98,99};//小写abc的ASSCA表示
String str3=new String(byteArray);
System.out.println("字符串str1是:"+str1+"\n字符串str2是:"+str2+"\n字符串str3是:"+str3);
2.String类的基本方法
(1)//length()用法 注意:数组.length没有括号,字符串.length()有括号
int t1="helloworld".length();
System.out.println("长度为:"+t1);
(2)//charAt()用法
char t2="helloworld".charAt(1);
System.out.println(t2);
(3)//indexOf()方法
int t3="helloworld".indexOf("llo");
System.out.println(t3);
(4)//contact()用法
String t4="hello";
String t5="world";
String t6=t4.concat(t5);
System.out.println(t6);
(5)equals()方法
注意区分equals和==。==是对象的地址的比较
public boolean equals(Object obj):参数可以是任何对象,***只有参数是一个字符串并且内容相同才返回ture***
(任何对象都能用Object进行接收)
String str="I love you"
如果“helloworld”与str进行比较,记得把字符串放在equals前面,否则当“***”是空字符串的时候会出现NullpointerException报错(“helloworld”.equals(str)是对的)
(6)字符串的截取substring()
public String substring(int index):截取从参数位置一直到字符串末尾,返回新的字符串(从0开始)
public String substring(int begin,int end):截取从begin开始到end结束的字符串【begin,end)包含左边,不含右边
(7)字符串的转化
public char[] tocharArray();将当前字符串拆成一个字符数组
public byte[] getBytes();获得当前字符串底层的字节数组
public String replace(Charsequence oldstring ,charsequence newstring);将所有出现的老字符串替换成新的字符串
charsequence是个接口,这里你把它理解成可以接受字符串类型就可以了
**char[] array1="hello".tocharArray();
byte[] array2="hello".getBytes();**
******
**String str1="How do you do";
String str2=str1.replace("o","k");**
当然中文也可以替换