1、String类
初始化
使用双引号创建的字符串,如果内容相同,那么都是同一个对象
用equals判断字符是否一样
import com.test.*;
public class Main {
public static void main(String [] argv)
{
String s="hello";
String s1=new String("hello");
String s2="hello";
//== 判断是否同一个对象
System.out.println(s==s2);//true
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
}
}
常用方法:
import com.test.*;
public class Main {
public static void main(String [] argv)
{
String s="hello";
String s1="how are you";
System.out.println(s.length());//5
System.out.println("world".length());//5
System.out.println(s.substring(0,3));//hel
System.out.println(s.substring(s.length()-2,s.length()));//lo
String s2[]=s1.split(" ");
for(String i:s2)
System.out.print(i+"---");//how---are---you---
System.out.println();
char c[]=s.toCharArray();
System.out.println(c);//hello
String s3=new String(c);
System.out.println(s3);//hello
}
}
import com.test.*;
public class Main {
public static void main(String [] argv)
{
String str = "Hello world!";
//第一次出现位置
System.out.println(str.indexOf("world")); // 6
//下标3开始l第一次出现位置
System.out.println( str.indexOf("l", 3));//3
//转换为字符串
System.out.println(123);//123
//是否空
System.out.println(str.isEmpty());//false
//转换为char类型
char c=str.charAt(3);//下标
System.out.println(c);
}
}
2、StringBuilder类
用于字符串处理,进行优化,减少字符对象的建立
import com.test.*;
public class Main {
public static void main(String [] argv)
{
String s1="1";
String s2="2";
String s3="3";
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(s1).append(s2).append(s3);
System.out.println(stringBuilder);//123
}
}
import com.test.*;
public class Main {
public static void main(String [] argv)
{
String s1="1";
String s2="2";
String s3="3";
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(s1).append(s2).append(s3);
String str=stringBuilder.toString();
System.out.println(str); //123
stringBuilder.delete(1,2);
System.out.println(stringBuilder);//13
}
}