String
1
、 实列化String字符串
直接赋值(这种方式合理些,内存占用少)
使用关键字new(相当于开辟了两个)
两个字符串比较使用 == 比较的是地址 equals比较的是内容
String字符串的内容不可更改
常用方法:
字符串长度:length()
字符串转换成数组:toCharArray()
从字符串中取出指定位置的字符:charAt()
字符串与Byte数组的转换:getBytes()
过滤字符串中存在的字符:indexOf()
去掉字符串的前后空格:trim()
从字符串中取出子字符串:subString()
大小写转换:toLowerCase()
toUpperCase()
判断字符串的开头结尾字符:endsWith() startWith()
替换字符串中的一个字符:replace()
2、StringBuffer:
缓冲区,本身也是操作字符串,但是与String不同,Stringbuffer是可以更改的
StringBuffer是一个操作类,所以必须通过实列化进行操作
常用方法:
append:追加
insert:插入
replace:替换
indexOf:
StringBuffer的应用:
速度快、占内存少
3、
StringBuilder:
一个可变的字符序列,该类设计作用StringBuffer的一个简易替换,用在字符串缓冲区被单个线程使用的时候。优先考虑该类,速度比StringBuffer要快
但是如果设计到线程安全方面,建议使用StringBuffer
常用方法:
append:追加
insert:插入
代码:
1、
package N07;
public class N1 {
/**String字符串
* @param args
*/
public static void main(String[] args) {
//
String str = "hello";
//
String str = new String("hello");
//
int a = 10;
//
int b = 10;
//
System.out.println(a == b);
//
String str01 = "Hello";
//
String str02 = new String("Hello");
//
//
System.out.println(str01 == str02);
//
//两个字符串比较使用这种方式 == 比较的是地址 equals比较的是内容
//
System.out.println(str01.equals(str02));
//
//
String str = "hello";
//hello开辟空间
//
str += "world";
//world要开辟空间 helloworld也要开辟空间
//
System.out.println(str);
StringBuffer sb = new StringBuffer();
sb.append("jlran");
tell(sb);
System.out.println(sb);
}
public static void tell(StringBuffer sb){
sb.append(" I love you");
}
}