想必大家都学习过c语言吧?那么我想问个问题,你们觉得C语言中有字符串类型吗?其实没有。C语言中要表示字符串类型只能使用字符数组和字符指针来表示,但是这种将数据和操作数据方法分离开的方式不符合面相对象的思想,而字符串应用又非常广泛,所以Java专门提供了String类。既然Java有String类,那么我们应该如何定义与使用呢?接下来就来帮你解答。
String类提供的构造方法很多,但是常用的就三种,分别是使用常量字符串构造,使用new String对象和使用字符数组构造
String str = "hello world";
String str = new Sreing("hello world");
char[] arr = {‘a',’b‘,’c‘};
String str = new String(arr);
虽然java有String类,但是并不是基本类型,它是引用类型,内部并不存储字符串本身,字符串实际保存在char类型的数组中,也就是说String内部中还存在着其它东西,存在着char[] value和int hash,我们不说这个。那么如果两个String类的字符串一样,那么它们是否相等呢?
int a = 10;
int b = 20;
int c = 10;
// 对于基本类型变量,==比较两个变量中存储的值是否相同
System.out.println(a == b); // false
System.out.println(a == c); // true
// 对于引用类型变量,==比较两个引用变量引用的是否为同一个对象
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
String s4 = s1;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
System.out.println(s1 == s4); // true
这就告诉你答案了。
讲完这个,就轮到我们应该最为关心的遍历了吧?
我们通常是用这种方法
String str = "dfsdsdf"; for (int i = 0; i < str.length(); i++) {char a = str.charAt(i) }
还有其他种,不过这种应该是最为常用的