5.1 String类

This commit is contained in:
seahi 2024-11-06 13:16:26 +08:00
parent cf6183c5b8
commit 58ad0dd15a
6 changed files with 104 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package chapter5;
public class Example01 {
public static void main(String[] args) {
// 1创建一个空的字符串
String str1 = new String();
// 2创建一个内容为abcd的字符串
String str2 = new String("abcd");
// 3创建一个内容为字符数组的字符串
char[] charArray = new char[]{'D', 'E', 'F'};
String str3 = new String(charArray);
// 4创建一个内容为字节数组的字符串
byte[] arr = {97, 98, 99};
String str4 = new String(arr);
System.out.println("a" + str1 + "b");
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
}

View File

@ -0,0 +1,13 @@
package chapter5;
public class Example02 {
public static void main(String[] args) {
String s = "abcdabc";
System.out.println("字符串的长度为:" + s.length());
System.out.println("字符串中第一个字符:" + s.charAt(0));
System.out.println("字符c第一次出现的位置:" + s.indexOf('c'));
System.out.println("字符c最后一次出现的位置:" + s.lastIndexOf('c'));
System.out.println("子字符串ab第一次出现的位置" + s.indexOf("ab"));
System.out.println("子字符串ab字符串最后一次出现的位置" + s.lastIndexOf("ab"));
}
}

View File

@ -0,0 +1,24 @@
package chapter5;
public class Example03 {
public static void main(String[] args) {
String str = "abcdEFG";
// 1转换成字符数组
System.out.print("将字符串转为字符数组后的结果:");
char[] charArray = str.toCharArray();
for (char c : charArray) {
System.out.print(c); // 打印当前遍历到的字符
System.out.print(','); // 每打印一个字符后加一个逗号
}
// 2把数字转换成字符串好用
System.out.println();
System.out.print("把数字123转换成字符串的效果");
System.out.println(String.valueOf(123));
// 3大小写转换常用
System.out.println("转换成小写:" + str.toLowerCase());
System.out.println("转换成大写:" + str.toUpperCase());
}
}

View File

@ -0,0 +1,16 @@
package chapter5;
public class Example04 {
public static void main(String[] args) {
String name = "王小明";
String newName = name.replace("", "");
System.out.println("旧名字:" + name + "\n新名字" + newName);
System.out.println();
String name2 = " 王 小明 ";
String name3 = name2.trim();
System.out.println("去除空格前:" + name2 + "\n去除空格后" + name3 );
// 思考如何去掉所有空格
}
}

View File

@ -0,0 +1,14 @@
package chapter5;
public class Example05 {
public static void main(String[] args) {
String s1 = "我是王小明";
String s2 = "我是";
System.out.println("判断开头:" + s1.startsWith("我是"));
System.out.println("判断结尾:" + s1.endsWith("小明"));
System.out.println("判断包含:" + s1.contains(""));
System.out.println("判空:" + s1.isEmpty());
System.out.println("判断相等:" + s1.equals(s2));
}
}

View File

@ -0,0 +1,16 @@
package chapter5;
public class Example06 {
public static void main(String[] args) {
String str = "石家庄-武汉-哈尔滨";
// 1截取
System.out.println("从第5个字符截取到末尾" + str.substring(4));
System.out.println("从第5个字符截取到第6个字符" + str.substring(4, 6));
// 2分割
System.out.println("分割后字符串数组中的元素依次是:");
String[] array = str.split("-");
for (String s : array) {
System.out.println(s);
}
}
}