创建字符串
创建字符串有以下几种方法:
1. String(char a[])方法
解释说明:用一个字符数组创建String对象
举例说明:
char a[]={'a','b','c'};
String s=new String(a);
和String s=new String("abc");是一样
- String(char a[],int offset,int length)
解释说明:提取字符数组中的一部分创建一个字符串对象。参数offset表示开始截取字符串的位置,length表示截取字符串的长度
举例说明:
public class StringBean {
public static void main(String[] args) {
char a[]={'a','b','c','d','e','f','g'};
String s=new String(a);
System.out.println(new String(a, 1, 5));
}
}
结果是:bcdef
值得注意的是参数int offset和int length不能随便给值,要根据参数char a[]的长度来决定,不然就会报错,下边就是错误的赋值,所造成的错误
public class StringBean {
public static void main(String[] args) {
char a[]={'a','b','c','d','e','f','g'};
String s=new String(a);
System.out.println(new String(a, 1, 9));
}
}
程序报错,输出String index out of range(字符串索引超出范围),因为字符串的长度最长是7,所以报错
public class StringBean {
public static void main(String[] args) {
char a[]={'a','b','c','d','e','f','g'};
String s=new String(a);
System.out.println(new String(a, 5, 3));
}
}
程序报错,输出String index out of range: 8
总结:参数int offset和参数int length的和不能大于字符数组char a[]的最大长度
3. 直接赋值
String str1,str2;
str1="student";
str2="student";
连接多个字符串
public class StringBean {
public static void main(String[] args) {
String str1="我";
String str2="是";
String str3="学生";
String str4=str1+str2+str3;
System.out.println(str4);
}
}
程序输出:我是学生
连接其他数据类型
public class StringBean {
public static void main(String[] args) {
String str1="我";
String str2="是";
String str3="学生";
String str4=str1+str2+str3+"已经学习了";
int i=10;
String str5=str4+i+"个小时";
System.out.println(str5);
}
}
程序输出:我是学生已经学习了10个小时
获取字符串信息
- 获取字符串的长度
解释说明:使用String类的length()方法可获取声明的字符串对象的长度
语法如下:
String str="qwerty";
int size=str.length();
- 字符串的查找
(1)indexOf(String s)
解释说明:该方法用于返回参数字符串s在指定字符串中首次出现的索引位置。当调用字符串的indexOf()方法时,会从当前字符串的开始位置搜索s的位置;如果没有检索但字符串s,该方法的返回值是-1。
语法如下:
str.indexOf(substr)
str:为任意的字符串对象
substr:要搜索的字符串
(2)lastIndexOf(String str)
解释说明:该方法用于返回最后一次出现的索引的位置。当调用字符串的lastIndexOf(String str)方法时。会从当前字符串的开始位置检索参数字符串的开始位置检索参数字符串str,并将最后一次出现str的索引位置返回。如果没有检索到字符串str,该方法返回-1.
语法如下:
str.lastIndexOf(substr)
str:任意字符串对象
substr:要搜索的字符串
- 获取指定索引位置的字符
(1)charAt(int index)
解释说明:使用charAt(int index)方法可将指定索引处的字符返回
语法说明:
str.charAt(int index)
str:任意的字符串
index:整型值,用于指定要返回字符的下标