练习1:其他PAI练习
import java.util.Arrays;
public class Demo4 {
public static void main(String[] args) {
String s = "abcdef";
// String类的替换功能
//在新的字符串中,用新(new)字符,替换旧(old)字符
//String replace(char old,char new)
//
//在新的字符串中,用新的字符串(new), 替换旧(old)字符串
//String replace(String old, String new)
String s1 = s.replace("ef", "xyz");
System.out.println(s1);
//在新的字符串中,去掉开头和结尾的空格字符
//String trim()
String s2 = " aaa ";
System.out.println("s2.trim() = " + s2);
System.out.println("s2.trim() = " + s2.trim());
//分隔功能
//将字符串按照符号分隔成字符串数组 "a,b,c,d"
//String[] split(String re)
String s3 = "a#b#c#d";
String[] split = s3.split("#");
System.out.println(Arrays.toString(split));
}
}
练习2:
需求:
1.给出一个英文句子:“i want a bing dun dun”
2.每个单词的首字母都转换为大写并输出
3.使用 solit() 方法
代码实现:
import java.util.Arrays;
public class Ex5 {
public static void main(String[] args) {
// 定义一个字符串
String s = "i want a bing dun dun";
// 使用split 按照空格进行分割
String[] split = s.split(" ");
System.out.println(Arrays.toString(split));
// 得到字符串数组
// 定义空字符串 用于拼接
String newStr = "";
for (String str : split) {
// 遍历字符串数组
// 把每个字符串的首字母拿出来 转换
String concat = str.substring(0, 1).toUpperCase().concat(str.substring(1));
// 重写拼接
newStr += concat + " ";
}
// 输出结果
System.out.println(newStr.trim());
}
}
练习3:自然排序
需求:
1.将字符串bdcage
2.对字符中的字符进行排序,最终得到abcdefg
代码实现:
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
String s = "bdcaegf";
// 转换为字符数组
char[] chars = s.toCharArray();
System.out.println("排序前:");
System.out.println(Arrays.toString(chars));
// 排序算法
//bubbleSort(chars);
// 简单方法 借助Arrays
Arrays.sort(chars);
System.out.println("排序后:");
System.out.println(Arrays.toString(chars));
// chars ---> String
String s1 = new String(chars);
System.out.println(s1);
}
private static void bubbleSort(char[] chars) {
for (int i = 0; i < chars.length - 1; i++) {
for (int j = 0; j < chars.length - 1 - i; j++) {
// 核心思想 两两交互 大的放后面 小的放前面
if (chars[j] > chars[j + 1]) {
// 使用临时变量做交换
char temp = chars[j];
chars[j] = chars[j + 1];
chars[j + 1]= temp;
}
}
}
}
}