StringTest02.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package course.api.string;
  2. import java.util.Arrays;
  3. /**
  4. * @author WanJl
  5. * @version 1.0
  6. * @title StringTest02
  7. * @description
  8. * @create 2026/7/27
  9. */
  10. public class StringTest02 {
  11. public static void main(String[] args) {
  12. String str1 = " hello world ";
  13. String str2 = " Hello World ";
  14. //比较字符串是否相同,比较的是内容,区分大小写。
  15. boolean b = str1.equals(str2);
  16. System.out.println(b);
  17. //比较字符串是否相同,比较的是内容,不区分大小写
  18. boolean b1 = str1.equalsIgnoreCase(str2);
  19. System.out.println(b1);
  20. ////返回字符串的长度
  21. int length = str1.length();
  22. System.out.println(length);
  23. //获取指定字符,返回索引值为2的那个字符。
  24. char c = str1.charAt(2);
  25. System.out.println(c);
  26. //截取字符串[0,5] 包含 0 索引,不包含5索引
  27. String subStr = str1.substring(0, 5);
  28. System.out.println(subStr);
  29. //查找子字符串位置,没有找到返回-1,返回这个子字符串在str1字符中第一次出现的位置
  30. int i = str1.indexOf("lo");
  31. System.out.println(i);
  32. // 判断str1字符串中是否包含 world 字符串
  33. boolean b2 = str1.contains("world");
  34. System.out.println(b2);
  35. //判断str1字符串是否以he开头
  36. str1.startsWith("he");
  37. //判断str1字符串是否以he结尾
  38. str1.endsWith("he");
  39. //字符串转大写
  40. String upperCase = str1.toUpperCase();
  41. System.out.println(upperCase);
  42. //字符串转小写
  43. String lowerCase = str1.toLowerCase();
  44. System.out.println(lowerCase);
  45. //去掉首尾空格
  46. String trim = str1.trim();
  47. System.out.println(trim);
  48. //去除全角/半角空格 JDK11+才有
  49. String strip = str1.strip();
  50. System.out.println(strip);
  51. //把旧的字符串(第1个参数)替换为新的字符串(第2个参数)
  52. String replace = str1.replace("world", "java");
  53. System.out.println(replace);
  54. //按照 字符 , 把字符串分割成字符串数组
  55. String s3="王艳阳,赵援翔,王嘉宇,王德昱,刘铭达,吴限,陈健,白立伟,田烁楠,王贺,赵颜,马莺莺,那洪舰,谷娜颖,孙宁,李时光,李昌龙,符荣里,吴壮,司一祺,徐振国";
  56. String[] split = s3.split(",");
  57. System.out.println(Arrays.toString(split));
  58. //判断字符串是否为空(长度为0)
  59. boolean empty = str1.isEmpty();
  60. System.out.println(empty);
  61. // 判断字符串是否为空或空白字符--JDK11+
  62. boolean blank = str1.isBlank();
  63. System.out.println(blank);
  64. //使用指定的字符,讲后面的每个字符串进行拼接
  65. String join = String.join("-", "A", "B", "C", "张三", "李四");
  66. System.out.println(join);
  67. }
  68. }