1、实例化String对象 直接赋值: String str="hello"; 使用关键字new: String str=new String("hello"); |
可以看出直接赋值节省了内存空间。
字符串的比较: |
package ds;
public class savg {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="hello";
String str1=new String("hello");
System.out.println(str==str1);
}
}
结果是:false ,所以使用双等无法进行比较
“==”比较的是地址,eqrals计较的是内容 |
所以得使用:System.out.println(str.equals(str1));
二:String字符串的内容不能更改 |
package ds;
public class savg {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="hello";
String str1=str+"world";
System.out.println(str1);
}
}
结果是:helloworld
三:String字符串的常用方法
1:字符串长度length()方法
String str = “wolaile”;
System.out.println(str.length());
2:字符串转换为数组:通过toCharArray();
package ds;
public class dabd {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "wolaile";
char ga[]=str.toCharArray();
System.out.println(ga);
}
}
**3:从字符串中取出指定位置的字符:charAt();**
package ds;
public class dabd {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "wolaile";
//char ga[]=str.toCharArray();
//System.out.println(ga);
System.out.println(str.charAt(3));
}
}
//结果是a
**4:字符串与Byte数组的转换:getBytes();**
package ds;
public class test45 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "wolaile";
byte jy[]=str.getBytes();
System.out.println(jy);
System.out.println(new String(jy));
}
}
**5:显示字符对应的下角标:indexOf();**
package ds;
public class eyh {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "wolaile@";
System.out.println(str.indexOf("@"));
}
}
**6:去掉字符串的前后空格:trim()**
package ds;
public class eyh {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = " wolaile@";
//System.out.println(str.indexOf("@"));
System.out.println(str.trim());
}
}
![这里写图片描述](https://img-blog.csdn.net/20180331105729295?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d6MTI0NTE5MTE0NQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
(https://blog.csdn.net/qq_37267015/article/details/59627656)