替换功能

  • String replace(char old, char new);
  • String replace(String old, String new);

    1. /**
    2. * String类的字符串替换
    3. */
    4. private static void demo1() {
    5. //演示String类的替换功能
    6. String s = "hello world";
    7. String s1 = s.replace("world","axin");
    8. System.out.println(s);//hello world
    9. System.out.println(s1);//hello axin
    10. String replace = s.replace("hhh", "www");
    11. System.out.println(replace); //hhh不存在的情况下,保持不变
    12. }

    去除字符串及两边空格

  • String trim();

    1. /**
    2. * 去除字符串两端的空格
    3. */
    4. private static void demo2() {
    5. String s = " hello world ";
    6. String trim = s.trim();
    7. System.out.println(s);//" hello world "
    8. System.out.println(trim);//hello world //只替换两端的空格
    9. }

    按字典排序比较两个字符串

  • int compareTo(String str)

  • int compareToIgnoreCase(String str)
  1. public static void main(String[] args) {
  2. String s1 = "bcdef";
  3. String s2 = "a";
  4. /*
  5. s1 < s2 结果为小于0的数
  6. s1 = s2 返果为0
  7. s1 > s2 结果为大于0的数
  8. */
  9. int i = s1.compareTo(s2);//按照码表值比较 unicode码表值
  10. System.out.println(i);
  11. String s3 = "中";
  12. String s4 = "国";
  13. int i1 = s3.compareTo(s4);
  14. System.out.println('中' + 0);//20013
  15. System.out.println('国' + 0);//22269
  16. System.out.println(i1);//-2256
  17. String s5 = "ABC";
  18. String s6 = "abc";
  19. System.out.println(s5.compareTo(s6));//-32
  20. System.out.println(s5.compareToIgnoreCase(s6));//0
  21. /*
  22. compareToIgnoreCase()的源码:
  23. public int compare(String s1, String s2) {
  24. int n1 = s1.length();
  25. int n2 = s2.length();
  26. int min = Math.min(n1, n2);
  27. for (int i = 0; i < min; i++) {
  28. char c1 = s1.charAt(i);
  29. char c2 = s2.charAt(i);
  30. if (c1 != c2) {
  31. c1 = Character.toUpperCase(c1); //防止一个大写 一个小写,统一转换成大写
  32. c2 = Character.toUpperCase(c2);
  33. if (c1 != c2) {
  34. c1 = Character.toLowerCase(c1); //统一转换成小写
  35. c2 = Character.toLowerCase(c2);
  36. if (c1 != c2) {
  37. // No overflow because of numeric promotion
  38. return c1 - c2;
  39. }
  40. }
  41. }
  42. }
  43. return n1 - n2;
  44. }
  45. */
  46. }