自学Java(day7)
一.String类概述
-
java.lang.String 类代表字符串,String类定义的变量可以用于指向字符串对象,然后操作该字符串。
-
Java 程序中的所有字符串文字(例如“abc”)都为此类的对象。
-
String其实常被称为不可变字符串类型,它的对象在创建后不能被更改。
-
字符串对象在字符串常量池中存储,以""方式给出的字符串对象。
- String是什么,可以做什么?
-
字符串类型,可以定义字符串变量指向字符串对象。
2.String是不可变字符串的原因?
-
String变量每次的修改其实都是产生并指向了新的字符串对象。
-
原来的字符串对象都是没有改变的,所以称不可变字符串。
二.String类的常用API-字符串内容比较
1.字符串的内容比较
- 字符串的内容比较不适合用"=="比较。
方法名 | 说明 |
---|---|
public boolean equals (Object anObject) | 将此字符串与指定对象进行比较。只关心字符内容是否一致! |
public boolean equalsIgnoreCase (String anotherString) | 将此字符串与指定对象进行比较,忽略大小写比较字符串。只关心字符内容是否一致! |
- 只关心内容是否一样就使用String提供的equals方法
- 基本数据类型比较是一般使用“==”。
2.案例
public class StringEqualsDemo {
public static void main(String[] args) {
//1.正确登陆名和密码
String okName = "张飞";
String okPassword = "123456";
//2.输入登陆名称和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入登陆名:");
String name = sc.next();
System.out.println("请输入密码:");
String password = sc.next();
//3.判断用户输入的登陆名称和密码是否正确
if(okName.equals(name) && okPassword.equals(password)){
System.out.println("登陆成功!欢迎您回来哟");
}else {
System.out.println("你输入的登录名或者密码有误!请重新输入哦");
}
//4.忽略内容大小写比较内容的api;一般用于比较验证码这样的逻辑业务
String code1 = "1WeQr2";
String code2 = "1wEqR2";
System.out.println(code1.equals(code2));//flase
System.out.println(code1.equalsIgnoreCase(code2));//ture
}
}
三.String类常用API-遍历、替换、截取、分割操作
方法名 | 说明 |
---|---|
public int length() | 返回此字符串的长度 |
public char charAt(int index) | 获取某个索引位置处的字符 |
public char[] toCharArray(): | 将当前字符串转换成字符数组返回 |
public String substring(int beginIndex, int endIndex) | 根据开始和结束索引进行截取,得到新的字符串(包前不包后) |
public String substring(int beginIndex) | 从传入的索引处截取,截取到末尾,得到新的字符串 |
public String replace(CharSequence target, CharSequence replacement) | 使用新值,将字符串中的旧值替换,得到新的字符串 |
public String[] split(String regex) | 根据传入的规则切割字符串,得到字符串数组返回 |
public class StringAPIOtherDemo {
public static void main(String[] args) {
// 1. public int length() 返回此字符串的长度
String s = "突然好想你,五月天";
System.out.println(s.length());
// 2. public char charAt(int index) 获取某个索引位置处的字符
char a = s.charAt(4);
System.out.println(a);
System.out.println("-------------遍历字符串的中的每个字符----------");
for (int i = 0; i < s.length(); i++) {
System.out.print(s.charAt(i));
}
System.out.println();
// 3. public char[] toCharArray(): 将当前字符串转换成字符数组返回
char[] chars = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char ch = chars[i];
System.out.print(ch+"\t");
}
System.out.println();
// 4. public String substring(int beginIndex, int endIndex) 根据开始和结束索引进行截取,得到新的字符串(包前不包后)
String rs = s.substring(2,5);
System.out.println(rs);
// 5. public String substring(int beginIndex) 从传入的索引处截取,截取到末尾,得到新的字符串
String rs1 = s.substring(6);
System.out.println(rs1);
// 6. public String replace(CharSequence target, CharSequence replacement) 使用新值,将字符串中的旧值替换,得到新的字符串
String rs3 = s.replace("五月天","***");
System.out.println(rs3);
// 7. public String[] split(String regex) 根据传入的规则切割字符串,得到字符串数组返回
String rs4 = "刘备,关羽,张飞";
String [] name = rs4.split(",");
for (int i