1、String的创建
// 直接创建
String s1 = "abc";
// new一个
String s2 = new String("abc");
2、字符串比较 “==” 、“equals” 、“equalsIgnoreCase”
(1)“==”
// 等值在引用类型中比较的是地址
// 字符串复值,首先在串池里面找有无相应的字符串,没有,创建一个,有把字符串的地址赋给该变量
// 优点:可以节约空间
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2); //true
String s3 = new String("abc");
System.out.println(s1 == s3); //false
(2)"equals" ,字符串内容之间比较,区分大小写
String s1 = "abc";
String s2 = "abc";
boolean result1 = s1.equals(s2);
System.out.println(result1); // true
String s3 = new String("abc");
boolean result2 = s1.equals(s3);
System.out.println(result2); // true
String s4 = "Abc";
boolean result3 = s4.equals(s1);
System.out.println(result3); // false 区分大小写
(3)"equalsIgnoreCase" 字符串比较忽略大小写
String s1 = "abc";
String s2 = "ABc";
boolean result = s1.equalsIgnoreCase(s2);
System.out.println(result); // true
注:键盘录入也是属于new
3、遍历字符串
将字符串转换为数组 :charAt()
String src = "abcd";
for(int i = 0; i < src.length(); i++){ //对数组用.length,对字符串用.length()
char c = src.charAt(i);
System.out.println(c); // a b c d
}
4、字符串拼接和反转
(1)拼接
public class lqb {
public static void main(String[] args) {
int[] array = {1,2,3};
System.out.print("[");
for(int i = 0; i < array.length; i++) {
System.out.print(i == array.length - 1? array[i] + "]" : array[i] + ", ");
}
}
(2)反转
public class lqb {
public static void main(String[] args) {
String src = "abcde";
for(int i = src.length() - 1; i >= 0; i--) {
System.out.print(src.charAt(i));
}
}
}
public class lqb {
public static void main(String[] args) {
String src = "abcde";
String result = "";
for(int i = src.length() - 1; i >= 0; i--) {
char c = src.charAt(i);
result += c;
}
System.out.println(result);
}
}