|
Java中没有字符串类型,字符串属于对象,Java 提供了 String 类来创建和操作字符串。"潘多码智能毕设辅导平台" 双引号中间的内容就是字符串。
常见创建字符串的方式 String type1 = "潘多码智能毕设辅导平台"; //一般直接用双引号中间写内容的方式
String type2 = new String("panduoma888");常用的操作字符串的方法
- 拼接字符串
//直接使用 + 号拼接字符串
String type1 = "潘多码智能毕设辅导平台";
String type2 = new String("panduoma888");
String r = type1 + type2;
System.out.println("r=" + r); // r=潘多码智能毕设辅导平台panduoma888
//使用concat方法拼接字符串
r = type1.concat(type2);
System.out.println("r=" + r);
- 获取字符串长度
//使用 length() 方法获得字符串长度
String type1 = "潘多码智能毕设辅导平台";
System.out.println("字符串长度=" + type1.length());
- 比较两个字符串内容是否一样
//使用 equals 方法比较两个字符串是否一样
String name = "潘多码智能毕设辅导平台";
String byb = "毕业帮帮毕业";
String name1 = "毕业帮帮毕业";
System.out.println(name.equals(byb)); // false
System.out.println(byb.equals(name1)); // true
//使用 equalsIgnoreCase 比较字符串时候 忽略大小写
String name = "panduoma";
String byb = "PANDUOMA";
System.out.println(name.equals(byb)); // false
System.out.println(name.equalsIgnoreCase(byb)); //true
- 查找字符串中字符的位置
// 使用 indexOf 查找第一次出现的指定的字符串在此字符串中的索引位置
String name = "panduomaduo";
System.out.println(name.indexOf("duo")); // 3 注意索引是从0开始
- 截取字符串
//使用 substring 截取字符串
String name = "panduomaduo";
System.out.println(name.substring(0,8)); // panduoma
System.out.println(name.substring(0,name.lastIndexOf("duo"))); // panduoma
System.out.println(name.substring(8)); // duo
- 字符串替换
String name = "banpuomaduo";
name = name.replaceAll("banpuo","panduo");
System.out.println(name); // panduoma
- 字符串分割
String name = "panduoma#888#iloveyou";
String[] re = name.split("#");
System.out.println(re[0]); //panduoma
System.out.println(re[1]); //888
System.out.println(re[2]); //iloveyou
上面是常见的操作字符串的方法,String类中还有很多方法,可以自己去看看具体的使用方法。
StringBuffer 操作字符串 StringBuffer buffer = new StringBuffer("panduoma"); // 创建
buffer.append(" 666"); //拼接
System.out.println(buffer);
String和StringBuffer 区别 String是字符串常量,它的值初始化后不可变,每次对String的操作都会生成新的String对象,会分配新的内存空间
StringBuffer是可变类,值可以变化,不会生成新的对象
本节课必知必会:
1、学会用String创建字符串,知道如何拼接字符串,了解String类中常见的7种操作方法
2、能知道StringBuffer是干什么的,能知道append方法的作用
本课练习
将本次课相关代码在Idea中敲一遍,达到必知必会中的要求。 |
|