学习目标:
目标:快速掌握 Java 入门知识
学习内容:
本文内容:学习Java中的String类,字符串的创建,字符串的比较, 字符、字节与字符串之间的相互转换等等。
文章目录
一、字符串的创建
常见的创建字符串的方法:
//方式一
String str1="Hello world";
//方式二
String str2=new String("Hello world");
//方式三
char[] array={'a','b','c'};
String str3=new String(array);
注意事项:
- String是引用类型。String str = “Hello”;这样的代码在内存中的布局如下:
- 对于这样的代码
String str1=“Hello”;
String str2=str1;
内存布局如下:
- 对于以下代码:
String str1=“Hello”;
str2=str1;
str1=“World”;
System.out.println(str2);
我们发现,“修改”str1之后str2的值不发生改变
这样的代码不会修改str1的值,只是将str1这个引用指向了一个新的String对象
内存布局如下:
二、比较字符串是否相等
Java中字符串的比较需要用到equals()方法,不能使用"==",因为String是引用类型,使用"=="会对两个字符串的地址进行比较
String str3=new String("Hello");
String str4=new String("Hello");
System.out.println(str3==str4);
//运行结果
false
equals()方法:
String str="hello";
System.out.println("hello".equals(str));
//运行结果
true
也可以写成以下形式,但是不建议这样写,因为如果str为空会报错而不是输出false
String str=“hello”;
System.out.println(str.equals(“hello”));
String str=null;
System.out.println(str.equals("hello"));
//运行结果
Exception in thread "main" java.lang.NullPointerException
at Java_vacation.A_string.main(A_string.java:38)
还有一个方法是equalsIgnoreCase(),使用这个方法比较字符串可以不区分大小
String str1="A";
String str2="a";
System.out.println(str1.equalsIgnoreCase(str2));
//运行结果
true
三、字符、字符数组与字符串之间的相互转换
1.从字符串中获取制定位置的字符的方法:charAt()
public class practice {
public static void main(String[] args) {
String str="helloworld";
System.out.println(str.charAt(0));
}
}
//运行结果
h
2.字符数组和字符串之间的相互转化
public class practice {
public static void main(String[] args) {
String str="helloworld";
//字符串转化为字符数组
char[] data=str.toCharArray();
System.out.print("字符数组data[]为:");
for(int i=0;i<data.length;i++){
System.out.print(data[i]+" ");
}
System.out.println();
// 字符数组转化为字符串
String str2=new String(data);//全部转化
String str3=new String(data,0,5);//部分转化
System.out.println("字符串str2:"+str2);
System.out.println("字符串str3:"+str3);
}
}
//运行结果
字符数组data[]为:h e l l o w o r l d
字符串str2:helloworld
字符串str3:hello
四、字节与字符串的相互转换
字符串转化为字节数组需要用到getBytes()方法
字节数组转化为字符串可直接将字节数组作为创建字符串时的变量
public class practice {
public static void main(String[] args) {
String str="hello";
byte[] data =str.getBytes();
System.out.print("字符串str转化的字节数组data[]为:");
for(int i=0;i<data.length;i++){
System.out.print(data[i]+" ");
}
System.out.println();
String newstr=new String(data);
System.out.print("字节数组data[]转化的字符串newstr为:");
System.out.println(newstr);
}
}
//运行结果
字符串str转化的字节数组data[]为:104 101 108 108 111
字节数组data[]转化的字符串newstr为:hello
五、比较字符串大小
比较字符串大小除了第二部分讲的还有一个方法可以返回字符串大小关系
**compareTo()**该方法返回一个整型,该数据会根据大小关系返回一下三类内容
1.相等:返回0;
2.小于:返回内容小于零;
3.大于:返回内容大于零;
**compareToIgnoreCase()**使用这个方法比较字符串大小可以忽视大小写
public static void Stringcompare() {
String str1="A";
String str2="a";
String str3="a";
System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str1));
System.out.println(str3.compareTo(str2));
System.out.println(str1.compareToIgnoreCase(str2));
}
//运行结果
-32
32
0
0
六、字符串查找:
字符串查找涉及的函数比较多,以下代码中都有较为详细的解释:
//字符串查找
public static void Stringsearch() {
String str1 = "hello world world world";
String str2 = "world";
//返回字符串某一位置的字符
System.out.println(str1.charAt(1));//e
//判断str1是否包含str2
System.out.println(str1.contains(str2));//true
//查找str1中str2的位置,返回str2开始的位置,没有找到返回-1
int result = str1.indexOf(str2);
System.out.println(result);//6
//从result + 1位置开始查找str2
int result2 = str1.indexOf(str2, result + 1);
System.out.println(result2);//12
// 从后向前开始查找str2
int result3=str1.lastIndexOf(str2);
System.out.println(result3);//18
//判断str1是否以str2开头/结尾
System.out.println(str1.startsWith(str2));//false
System.out.println(str1.endsWith(str2));//true
}
//运行结果
e
true
6
12
18
false
true
Process finished with exit code 0
七、字符串替换
字符串替换分为两种:
第一种是replaceAll():替换字符串中所有的某个子串;
第二种是replaceFirst():只替换字符串中第一次出现的某个子串;
public static void stringReplace() {
String str1="Hello Hello World";
System.out.println("替换前:"+str1);
String str2=str1.replaceAll("Hello","hello");
System.out.println("替换所有后:"+str2);
String str3=str1.replaceFirst("Hello","hello");
System.out.println("替换部分后:"+str3);
}
//运行结果
替换前:Hello Hello World
替换所有后:hello hello World
替换部分后:hello Hello World
八、字符串拆分
split(String regex):将字符串按照regex的内容进行拆分,结果保存到字符串数组中
split(String regex, int limit)//字符串按照空格拆分,返回的数组长度最大是limit
public static void stringSplit() {
String str="Hello world hello ";
String[] newstr1=str.split(" ");//字符串按照空格拆分
String[] newstr2=str.split(" ",2);//字符串按照空格拆分,返回的数组长度最大是2
System.out.println(Arrays.toString(newstr1));
System.out.println(Arrays.toString(newstr2));
//运行结果
[Hello, world, hello]
[Hello, world hello ]
//字符串多次拆分
String str2="name=zhangsan&age=18";
String[] result=str2.split("&");
for(int i=0;i<result.length;i++){
String[] temp=result[i].split("=");
System.out.println(temp[0]+"="+temp[1]);
}
//运行结果
name=zhangsan
age=18
}
九、字符串截取
substring(int beginIndex):从字符串beginIndex位置开始截取,一直到末尾;
substring(int beginIndex, int endIndex):从字符串beginIndex开始截取,一直到endIndex,包含beginIndex,不包含endIndex;
private static void stringCutOut() {
String str="Hello world";
System.out.println(str.substring(6));//截取下标6到末尾
System.out.println(str.substring(0,5));//截取下标[0,5)
}
//运行结果
world
Hello
十、字符串其他常见操作
trim():去除字符串str开头和结尾的空白字符(空格、换行、制表符等等)
toLowerCase():字符串转小写
toUpperCase():字符串转大写
length():返回字符串长度
isEmpty():判断字符串是否为空,需要注意的是这个方法判断字符串内容是否为空,为空则是String str ="";而不是字符串引用的指向是否为空,既String str=null
private static void other() {
String str =" Hello World ";
//去除字符串str开头和结尾的空白字符(空格、换行、制表符等等)
String str1=str.trim();
System.out.println("["+str1+"]");
String str2=str.toLowerCase();//字符串转小写
String str3=str.toUpperCase();//字符串转大写
System.out.println(str2);
System.out.println(str3);
int length=str.length();//返回字符串长度
System.out.println(length);
System.out.println(str.isEmpty());//判断字符串是否为空
}
//运行结果
[Hello World]
hello world
HELLO WORLD
13
false
十一、StringBuffer和StringBulider
回顾一下String特点:
任何字符串常量都是String类型的,而且String常量一旦声明不可改变,如果改变对象,只是改变了引用的指向而已,本身内容没有发生变化
为了方便修改字符串内容,提供了StringBuffer和StringBulider类,两者功能基本一致,我们这里介绍StringBuffer
观察StringBuffer的使用方法:
public static void stringBuffer() {
StringBuffer sb=new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb);
}
//运行结果
Hello World
可以很容易的发现StringBuffer对象赋值可以直接调用append()方法;
除了append()方法,StringBuffer还有几个比较常见的方法:
(这一部分也是比较容易理解,我就不做过多解释了)
public static void stringBuffer() {
StringBuffer sb = new StringBuffer("Hello world");
System.out.println(sb);
System.out.println(sb.reverse());//字符串反转
System.out.println(sb.reverse());//字符串反转
System.out.println(sb.delete(0, 5));//删除字符串某一部分
System.out.println(sb.insert(0, "hello"));//在字符串某一部分插入一部分内容
}
//运行结果
Hello world
dlrow olleH
Hello world
world
hello world