1.String类的初始化
有两种方式:
1.使用字符串常量直接初始化一个String对象:String str1="abc";
2.使用String类的构造方法初始化字符串对象,String类的构造方法如下所示:
方法声明 | 功能描述 |
---|---|
String() | 创建一个内容为空的字符串 |
String(char[] value) | 根据指定的字符数组创建对象 |
String(String value) | 根据指定的字符串内容创建对象 |
示例:
package jaj;
public class Example18 {
public static void main(String[] args) {
String str1=new String();//创建一个空的字符串
String str2=new String("abcd");//创建一个内容为abcd的字符串
char[] charArray=new char[] {'D','E','F'};
String str3=new String(charArray);//创建一个内容为字符数组的字符串
System.out.println("a"+str1+"b");
System.out.println(str2);
System.out.println(str3);
}
}
运行结果如图所示:
2 .String类的常见操作
1 字符串的基本操作:
package jaj;
public class Example19 {
public static void main(String[] args) {
String s="abbeujbff";
System.out.println("字符串的长度:"+s.length());
System.out.println("字符串第一个字符:"+s.charAt(0));
System.out.println("字符b第一次出现的位置:"+s.indexOf('b'));
System.out.println("字符b最后一次出现的位置:"+s.lastIndexOf('b'));
}
}
运行结果如图所示:
2 字符串的转换操作:
package jaj;
public class Example21 {
public static void main(String[] args) {
String str="abcd";
System.out.print("将字符串转换为字符数组后的结果:");
char[]ary=str.toCharArray();
for(int i=0;i<ary.length;i++) {
if(i!=ary.length-1)
System.out.print(ary[i]+",");
else System.out.println(ary[i]);
}
System.out.println("将int值转换为String类型之后的结果:"+String.valueOf(12));
System.out.println("将字符串转换为大写之后的结果:"+str.toUpperCase());
}
}
运行结果如图所示:
其中valueOf()方法有多种重载形式,float、double、char等其他基本类型的数据都可以通过该方法转为String字符串类型。
3 字符串的替换和去除空格操作:
分别用replace()和trim()方法
package jaj;
public class Example20 {
public static void main(String[] args) {
String s="itcast";
System.out.println("将it替换为cn.it的结果:"+s.replace("it", "cn.it"));
String s1=" i t c a s t ";
System.out.println("去除字符串两端空格后的结果:"+s1.trim());
System.out.println("去除字符串中所有空格后的结果:"+s1.replace(" ", ""));
}
}
运行结果如图所示: