String的概念和不变性
String类代表字符串。Java程序中所有字符串字面(如:“abc”)都作为此类的实例。
字符串是常量;它们的值在创建以后是不能被改变的。因为String对象是不可变的,所以可以共享。
String类的创建方式和比较
String类的创建
方式1.直接声明常量字符串String并赋值。 公式为:String 名 = “值”;
如:
String s = "abc";
1
方式2.
把字符串new成对象进行赋值。
公式为:String 名 = new String(“值”);
如:
String s = new String("abc");
1
String类的比较
String可以用“==操作符”和“equals方法”进行比较,两者的区别是:
1.==操作符
用于基本数据类型的比较。
判断内存地址是否相同。
2.equals方法
判断两者内容是否一样。
==进行比较
方式一赋值:
String s1 = "abc";
String s2 = "abc";
System.out.print(s1==s2);
1
2
3
返回值:
true
1
方式二赋值
String s1 = new String("abc");
String s2 = new String("abc");
System.out.print(s1==s2);
1
2
3
返回值:
false
1
总结:方式一赋值比较的是字符串内容,方式二赋值比较的是字符串的内存地址。
equals比较
同上赋值:方式一
System.out.print(s1.equals(s2));
1
返回值:
true
1
同上赋值:方式二
System.out.print(s1.equals(s2));
1
返回值
true
1
总结:equals比较的都是字符串的内容。
String类常用的方法
length方法
返回字符串的长度
public static void fun1(){
String string = "skjl";
int l = string.length();
System.out.println(l);
}
1
2
3
4
5
返回值:4
substring方法
获取字符串的一部分,包含头不包含尾,
substring(int beginlndex,int endlndex);
substring(int beginlndex)
public static void fun2(){
String s = "helloworld";
String s2 = s.substring(2);
System.out.println(s2);
}
1
2
3
4
5
返回值:lloworld
public static void fun2(){
String s = "helloworld";
String s1 = s.substring(1, 4);
System.out.println(s2);
}
1
2
3
4
5
返回值:ell
startsWith方法
判断一个字符串是否包含另一个字符串,返回布尔类型
public static void fun3(){
String s = "helloworld";
boolean s1 = s.startsWith("hello");
System.out.println(s1);
}
1
2
3
4
5
返回值:true
endsWith方法
判断一个字符串的后缀结尾,返回布尔类型
public static void fun4(){
String s = "hello.java";
boolean s1 = s.endsWith(".java");
System.out.println(s1);
}
1
2
3
4
5
返回值:true
contains方法
判断一个字符串是否有另外一个字符串
public static void fun5(){
String s = "hello.java";
boolean s1 = s.contains("ll");
System.out.println(s1);
}
1
2
3
4
5
返回值:true
inDex方法
查找一个字符下标,返回int型,如果返回-1则说明该字符串不存在该值。
public static void fun6(){
String s = "hello.java";
int s1 = s.indexOf('w');
System.out.println(s1);
}
1
2
3
4
5
返回值:-1
public static void fun1(){
String s = "hellojava";
int s1 = s.indexOf('j');
System.out.println(s1);
}
1
2
3
4
5
返回值:5
getBytes方法
将字符串转变为字节数组
public static void fun7(){
String s = "hellojava";
byte[] s1 = s.getBytes();
System.out.println(s1);
for (int i = 0; i < s1.length; i++) {
System.out.println(s1[i]);
}
}
1
2
3
4
5
6
7
8
返回值:s1返回的是s1的内存地址,s1[i]遍历的是ASCII码
toCharArray方法
将字符串转为字符数组
public static void fun8(){
String s = "hellojava";
char[] s1 = s.toCharArray();
for (int i = 0; i < s1.length; i++) {
System.out.println(s1[i]);
}
}
1
2
3
4
5
6
7
返回值:s1返回的是地址,遍历出来的是每个字符。
equals和equalslgboreCase方法
判断字符串内容是否相等,equals区分大小写,equalslgboreCase不区分大小写。
public static void fun9(){
String s = "hello";
String s1= "hEllo";
System.out.println(s.equals(s1));
System.out.println(s.equalsIgnoreCase(s1));
}
1
2
3
4
5
6
返回值:false true
================================================
下次更新StringBuffer和StringBuilder的用法!!!
---------------------
作者:guo12345555
来源: