最近从力扣刷题下来,发现字符串是考试的重灾区,下面将依据黑马官方相关视频进行总结:
String name = "阿伟";
String schoolName = "黑马程序员";
System.out.println(name + schoolName);
//产生一个新字符串,不改变原有字符串(字符串一旦创建不发生改变)
下面看一下字符串的创建
public class heimaString {
public static void main(String[] args) {
//方法1.
String s1 = "abc";
System.out.println(s1); //abc
//方法2. 使用new 的方法获取一个字符串对象
//空参构造: 可以获取一个空白的字符串对象
String s2 = new String(); //""
System.out.println("@" + s2 + "!"); //@!
//传递一个字符串,根据传递的字符串内容创建一个新的字符串对象
String s3 = new String("abc");
System.out.println(s3); //abc
//传递一个字符数组,根据字符数组的内容再创建一个新的字符串对象
char[] chs = {'a' , 'b' ,'c' , 'd'};
String s4 = new String(chs);
System.out.println(s4); //abcd
}
}
创建小贴士:用new方法时会在堆中开辟一个新的空间。(因此不推荐用)
那如果需要修改字符串怎么办呢?
方法一:
//基于上一题,需求:我要修改字符串的内容 abc->Qbc //因为字符串创立后无法修改,可以将其变为字符数组的形式修改下标索引
方法二:
//传递一个一个字节数组,根据字节数组的内容再创建一个新的字符串对象 //应用场景:以后在网络当中传输的数据其实都是字节信息 //我们一般要把字节信息惊醒转换,换成字符串,此时就需要用到这个构造了
byte[] bytes = {97 , 98, 99 , 100}; //这里对应的是ASCII码
String s5 = new String(bytes);
System.out.println(s5); //abcd
字符串的比较
1.如果是基本数据类型
int a = 10;
int b = 20;
System.out.println(a == b); //false
基本数据类型比较的是数据值
2.如果是引用数据类型
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println( s1 == s2 ); //false
引用数据类型比较的是地址值
那我这样,阁下又应该如何面对呢?
String s1 = new String("abc"); //记录堆里面的地址值
String s2 = "abc"; //记录串池里面的地址值
System.out.println(s1 == s2); //false
鸡同鸭讲,不可能正确
这里有一个通用的字符串内容比较方法
boolean equals方法(要比较的字符串) 完全一样的true, 否则false
boolean equalsIgnoreCase(要比较的字符串) 忽略大小写的比较
public class heimaString {
public static void main(String[] args) {
//假如现在键盘录入一个abc
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String str1 = sc.next();
//代码中再定义一个字符串abc
String str2 = "abc";
//用==比较,这两者能一样吗?
System.out.println(str1 == str2);
}
}
这里拓展一下:next这里也是在源码上用的new,堆中拓展出空间,_>false
字符串相关操作1.遍历
public class heimaString {
public static void main(String[] args) {
//假如现在键盘录入一个字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串");
String str = sc.next();
//进行遍历
for (int i = 0; i < str.length(); i++) {
//i依次表示字符串中的每一个索引
char c = str.charAt(i);
System.out.println(c);
}
}
}
public class heimaString {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6};
String str = arrToString(arr);
System.out.println(str);
}
public static String arrToString(int[] arr){
if(arr == null){
return "";
}
if(arr.length == 0){
return "[]";
}
String result = "[";
for (int i = 0; i < arr.length; i++) {
result = result + arr[i];
}
result = result + "]";
return result;
}
}
现在做一个反转
public class heimaString {
public static void main(String[] args) {
String result = reverser("abc");
System.out.println(result);
}
public static String reverser(String str){
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
result = result + c;
}
return result;
}
}