String类
1 字符串的声明
java中用字符串" "括起来
字符串的声明:String 字符串name;
声明及初始化:String str="hello";
2 创建字符串
用一个字符数组创建一个对象
char[] s={'h','e','l','l','o'};
String str=new String(a);
等价于String str=new String("hello");
提取字符数组中一部分创建一个字符串对象
char[] a={'s','t','u','d','e','n','t'};
String str=new String(a,2,4);
等价于String str=new String("uden");
引用字符串常量来创建字符串变量
String str1,str2;
str1="hello"
str2="hello"
此时Str1与Str2引用相同的字符串常量因此具有相同的实体。
3 连接字符串
public static void main(String[] args) {
String s1="hello";
String s2="java";
String s=s1+" "+s2;
System.out.println(s);
}
4 获取字符串长度
public static void main(String[] args) {
String s1="hello";
String s2="java";
int size1=s1.length();
int size2=s2.length();
System.out.println(size1);
System.out.println(size2);
}
5 字符串的查找
public class test {
public static void main(String[] args) {
String s1="hello";
String s2="java";
int size01=s1.indexOf("e");
int size02=s2.lastIndexOf("a");
char c=s1.charAt(4);
System.out.println(c);
System.out.println(size01);
System.out.println(size02);
}
}
6 获取子字符串 (字符串中空格占用一个索引)
public class test {
public static void main(String[] args) {
String s1="hello";
String s2="java";
String str=s1.substring(3);
String str2=s2.substring(0,3);
String str1=s2.substring(1,3);左闭右开
System.out.println(str2);
System.out.println(str);
System.out.println(str1);
}
}
7 去除空格
public class test {
public static void main(String[] args) {
String s1=" hello java ";
System.out.println(s1.length());
System.out.println(s1.trim().length());
}
}
8 字符串的替换
replace()方法将指定的字符或字符串换成新的字符或字符串
public class test {
public static void main(String[] args) {
String str="address";
String newstr=str.replaceAll("a", "A");
System.out.println(newstr);
}
}