String
字符串是常量,创建之后不可改变 字符串字面值存储在字符串池中,可以共享
package common.common03;
public class Demo01 {
public static void main(String[] args) {
String name="hello";//hello存在方法池中
name="zhangsan";//zhangsan赋值给name,给字符串赋值时,没有修改数据,而是重新开辟了一个空间
String name2="zhangsan";
//字符串的另一种创建方式
String str=new String("11111");
}
}
常用方法
public int length ( ) ; 返回字符串长度
public char charAt ( int index) ; 根据下标获取字符
public boolean contains(String str);判断当前字符串是否含有str
//字符串方法的使用
//1.length()返回字符串长度
//2。charAt(int index)返回某个位置的字符
//3.contains(String str) 判断是否包含某个字符串
String content="1223449499";
System.out.println(content.length());
System.out.println(content.charAt(0));
System.out.println(content.contains("33"));
System.out.println(content.contains("12"));
public char [ ] toCharArray ( ) : 将字符串转化
public int indexOf(String str);查找str首次出现的下标,存在,则返回该下标,不存在,则返回-1
public int lastIndexOf ( String str) ; 查找字符串在当前字符串中最后一次出现的下标
System . out. println ( Arrays . toString ( content. toCharArray ( ) ) ) ;
System . out. println ( content. indexOf ( 2 ) ) ;
System . out. println ( content. lastIndexOf ( 3 ) ) ;
public String trim();去掉字符串前后的空格
public String toUPperCase ( ) ; 将大写改成小写
public boolean endWith ( String str) 判断字符串是否以str结尾
String content2= " hello world " ;
System . out. println ( content2. trim ( ) ) ;
System . out. println ( content2. toUpperCase ( ) ) ;
System . out. println ( content2. endsWith ( " " ) )
public String replace ( char oldChar, char newChar) ; 将旧字符串替换成新字符串
public String [ ] split ( String str) 根据str做拆分
System . out. println ( content. replace ( "9" , "3" ) ) ;
String say= "java is the best programing language ,java" ;
String [ ] arr= say. split ( "[ ,]" ) ;
System . out. println ( arr. length) ;
for ( String string: arr) {
System . out. println ( string) ;
}
String s1= "hello" ;
String s2= "hello" ;
System . out. println ( s1. equals ( s2) ) ;
System . out. println ( s1. equalsIgnoreCase ( s2) ) ;
String s3= "abc" ;
String s4= "xyz" ;
System . out. println ( s3. compareTo ( s4) ) ;
可变字符串
StringBuffer:运行速率慢,线程安全 StringBuilder:运行效率快,线程不安全
StringBuilder sb = new StringBuilder ( ) ;
sb. append ( "java是一门很好的语言" ) ;
System . out. println ( sb. toString ( ) ) ;
sb. append ( "java真香" ) ;
System . out. println ( sb. toString ( ) ) ;
sb. append ( "java真不糗" ) ;
System . out. println ( sb. toString ( ) ) ;
sb. insert ( 0 , "我在最前面" ) ;
System . out. println ( sb. toString ( ) ) ;
sb. replace ( 0 , 5 , "hello" ) ;
System . out. println ( sb. toString ( ) ) ;
sb. delete ( 0 , 5 ) ;
System . out. println ( sb. toString ( ) ) ;
sb. delete ( 0 , sb. length ( ) ) ;
System . out. println ( sb. toString ( ) ) ;