一、字符串“打劫!我有枪”,“枪”是敏感词汇,替换为“*”,并输出打印
public class Demo01 {
public static void main(String[] args) {
String str = new String("打劫!我有枪”");
String str1="枪";
String s1 = str.replaceAll("枪", "*");
System.out.println("s1 = " + s1);
}
}
运行结果
s1 = 打劫!我有*”
二、字符串“北京欢迎你”,替换字符为“郑州欢迎你们”,并输出打印
public class Demo02 {
public static void main(String[] args) {
String str = "北京欢迎你";
String str2 = str.replaceAll("北京欢迎你", "郑州欢迎你们");
System.out.println(str2);
}
}
运行结果
郑州欢迎你们
三、字符串“面向对象是以对象为核心..编程思想”,获取并第一个下标和最后一个下标的字符,并输出打印
public class Demo03 {
public static void main(String[] args) {
String str = "面向对象是以对象为核心..编程思想";
String s[] = str.split("");
System.out.println(s[0]);
System.out.println(s[s.length-1]);
}
}
运行结果
面
想
四、将double类型的数据3.1415926转为字符串
public class Demo04 {
public static void main(String[] args) {
double d = 3.1415926;
String s = String.valueOf(d);
System.out.println("s="+s);
}
}
运行结果
s=3.1415926
七、基本数据类型、包装类、字符串String三者之间的相互转换
以int为例:
1.int->包装类
包装类->int
2.int->String
String->int
3.包装类->String
String->包装类
public class Demo07 {
public static void main(String[] args) {
int a=2;
String num = Integer.toString(a);
int b=Integer.parseInt(num);
}
}