day08-常用类-String-的转换&分割方法

This commit is contained in:
2026-01-20 16:02:57 +08:00
parent 33aca26c55
commit 71c2e2049d
3 changed files with 67 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
package com.inmind.string01;
/*
5.常用类-String-的转换方法
public char[] toCharArray () :将此字符串转换为新的字符数组。
public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
public String replace (CharSequence target, CharSequence replacement) 将与target匹配的字符串使用replacement字符串替换。
*/
public class Demo07 {
public static void demo1() {
//public char[] toCharArray () :将此字符串转换为新的字符数组。
String str = "abc";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.println(chars[i]);
}
}
public static void demo2() {
//public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组
String str = "abc";
byte[] bytes = str.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);
}
}
public static void main(String[] args) {
//public String replace (CharSequence target, CharSequence replacement) 将与target匹配的字符串使用replacement字符串替换。
String str = "今天,天气很好,我很高兴";
//想把str中所有的天都替换为*
String newStr = str.replace("", "***");
System.out.println(str);
System.out.println(newStr);
}
}

View File

@@ -0,0 +1,15 @@
package com.inmind.string01;
/*
public String[] split(String regex) 将此字符串按照给定的regex规则拆分为字符串数组。
*/
public class Demo08 {
public static void main(String[] args) {
String str = "hello,world,day,day,up";
//注意:按,切割,按什么分割,该字符串就不会出现
String[] strings = str.split(",");
System.out.println(strings);
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
}

View File

@@ -0,0 +1,16 @@
package com.inmind.string01;
public class Test09 {
public static void main(String[] args) {
//将字符串转为自定义类对象Student
String str1 = "1,张三,18";
String str2 = "2,李四,20";
String[] arr1 = str1.split(",");
Student s1 = new Student(arr1[1], Integer.parseInt(arr1[2]), Integer.parseInt(arr1[0]));
System.out.println(s1.getId());
System.out.println(s1.getName());
System.out.println(s1.getAge());
}
}