【Java】String类的常用方法

短命女 2023-09-28 22:23 76阅读 0赞

在这里插入图片描述博客主页: XIN-XIANG荣
系列专栏:【Java SE】
一句短话: 难在坚持,贵在坚持,成在坚持!

文章目录

  • 一. String对象的比较
      1. ==比较是否引用同一个对象
      1. boolean equals(Object anObject)
      1. int compareTo(String s)
      1. int compareToIgnoreCase(String str)
  • 二. 字符串查找
  • 三. 转化
      1. 数值和字符串转化
      1. 大小写转化
      1. 字符串和数组的转换
      1. 格式化
  • 四. 字符串替换
  • 五. 字符串拆分
  • 六. 字符串截取
  • 七. 其他操作方法
      1. String trim()
      1. boolean isEmpty ()
      1. int length()
      1. 判断字符串开头结尾
      1. boolean contains(String str)

一. String对象的比较

1. ==比较是否引用同一个对象

注意:

  • 对于内置类型,==比较的是变量中的值;对于引用类型 , == 比较的是引用中的地址。

    public static void main(String[] args) {

    1. int a = 10;
    2. int b = 20;
    3. int c = 10;
    4. // 对于基本类型变量,==比较两个变量中存储的值是否相同
    5. System.out.println(a == b); // false
    6. System.out.println(a == c); // true
    7. // 对于引用类型变量,==比较两个引用变量引用的是否为同一个对象
    8. String s1 = new String("hello");
    9. String s2 = new String("hello");
    10. String s3 = new String("world");
    11. String s4 = s1;
    12. System.out.println(s1 == s2); // false
    13. System.out.println(s2 == s3); // false
    14. System.out.println(s1 == s4); // true

    }

2. boolean equals(Object anObject)

按照字典序进行比较(字典序:字符大小的顺序)

String类重写了父类Object中equals方法,Object中equals默认按照==比较,String重写equals方法后,按照 如下规则进行比较,比如: s1.equals(s2)

String中的equals方法分析:

  1. public boolean equals(Object anObject) {
  2. // 1. 先检测this 和 anObject 是否为同一个对象比较,如果是返回true
  3. if (this == anObject) {
  4. return true;
  5. }
  6. // 2. 检测anObject是否为String类型的对象,如果是继续比较,否则返回false
  7. if (anObject instanceof String) {
  8. // 将anObject向下转型为String类型对象
  9. String anotherString = (String)anObject;
  10. int n = value.length;
  11. // 3. this和anObject两个字符串的长度是否相同,是继续比较,否则返回false
  12. if (n == anotherString.value.length) {
  13. char v1[] = value;
  14. char v2[] = anotherString.value;
  15. int i = 0;
  16. // 4. 按照字典序,从前往后逐个字符进行比较
  17. while (n-- != 0) {
  18. if (v1[i] != v2[i])
  19. return false;
  20. i++;
  21. }
  22. return true;
  23. }
  24. }
  25. return false;
  26. }

比较示例代码:

  1. public static void main(String[] args) {
  2. String s1 = new String("hello");
  3. String s2 = new String("hello");
  4. String s3 = new String("Hello");
  5. // s1、s2、s3引用的是三个不同对象,因此==比较结果全部为false
  6. System.out.println(s1 == s2); // false
  7. System.out.println(s1 == s3); // false
  8. // equals比较:String对象中的逐个字符
  9. // 虽然s1与s2引用的不是同一个对象,但是两个对象中放置的内容相同,因此输出true
  10. // s1与s3引用的不是同一个对象,而且两个对象中内容也不同,因此输出false
  11. System.out.println(s1.equals(s2)); // true
  12. System.out.println(s1.equals(s3)); // false
  13. }

3. int compareTo(String s)

按照字典序进行比较

与equals不同的是,equals返回的是boolean类型,而compareTo返回的是int类型。具体比较方式:

  • 先按照字典次序大小比较,如果出现不等的字符,直接返回这两个字符的大小差值
  • 如果前k个字符相等(k为两个字符长度最小值),返回值两个字符串长度差值

    public static void main(String[] args) {

    1. String s1 = new String("abc");
    2. String s2 = new String("ac");
    3. String s3 = new String("abc");
    4. String s4 = new String("abcdef");
    5. System.out.println(s1.compareTo(s2)); // 不同输出字符差值-1
    6. System.out.println(s1.compareTo(s3)); // 相同输出 0
    7. System.out.println(s1.compareTo(s4)); // 前k个字符完全相同,输出长度差值 -3

    }

4. int compareToIgnoreCase(String str)

与compareTo方式相同,但是忽略大小写进行比较

  1. public static void main(String[] args) {
  2. String s1 = new String("abc");
  3. String s2 = new String("ac");
  4. String s3 = new String("ABc");
  5. String s4 = new String("abcdef");
  6. System.out.println(s1.compareToIgnoreCase(s2)); // 不同输出字符差值-1
  7. System.out.println(s1.compareToIgnoreCase(s3)); // 相同输出 0
  8. System.out.println(s1.compareToIgnoreCase(s4)); // 前k个字符完全相同,输出长度差值 -3
  9. }

二. 字符串查找

字符串查找也是字符串中非常常见的操作,String类提供的常用查找的方法,














































方法 功能
char charAt(int index) 返回index位置上字符,如果index为负数或者越界,抛出 IndexOutOfBoundsException异常
int indexOf(int ch) 返回ch第一次出现的位置,没有返回-1
int indexOf(int ch, int fromIndex) 从fromIndex位置开始找ch第一次出现的位置,没有返回-1
int indexOf(String str) 返回str第一次出现的位置,没有返回-1
int indexOf(String str, int fromIndex) 从fromIndex位置开始找str第一次出现的位置,没有返回-1
int lastIndexOf(int ch) 从后往前找,返回ch第一次出现的位置,没有返回-1
int lastIndexOf(int ch, int fromIndex) 从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返 回-1
int lastIndexOf(String str) 从后往前找,返回str第一次出现的位置,没有返回-1
int lastIndexOf(String str, int fromIndex) 从fromIndex位置开始找,从后往前找str第一次出现的位置,没有返 回-1
  1. public static void main(String[] args) {
  2. String s = "aaabbbcccaaabbbccc";
  3. System.out.println(s.charAt(3)); // 'b'
  4. System.out.println(s.indexOf('c')); // 6
  5. System.out.println(s.indexOf('c', 10)); // 15
  6. System.out.println(s.indexOf("bbb")); // 3
  7. System.out.println(s.indexOf("bbb", 10)); // 12
  8. System.out.println(s.lastIndexOf('c')); // 17
  9. System.out.println(s.lastIndexOf('c', 10)); // 8
  10. System.out.println(s.lastIndexOf("bbb")); // 12
  11. System.out.println(s.lastIndexOf("bbb", 10)); // 3
  12. }

注意:

  • 上述方法都是实例方法,通过对象引用调用。

三. 转化

1. 数值和字符串转化

static String valueof() 数值转字符串

Integer.parseInt() 字符串整形

Double.parseDouble() 字符串转浮点型

  1. public class Test {
  2. public static void main(String[] args) {
  3. // 值转字符串
  4. String s1 = String.valueOf(1234);
  5. String s2 = String.valueOf(12.34);
  6. String s3 = String.valueOf(true);
  7. String s4 = String.valueOf(new Student("Hanmeimei", 18));
  8. System.out.println(s1);
  9. System.out.println(s2);
  10. System.out.println(s3);
  11. System.out.println(s4);
  12. System.out.println("=================================");
  13. // 字符串转数字
  14. //Integer、Double等是Java中的包装类型
  15. int data1 = Integer.parseInt("1234");
  16. double data2 = Double.parseDouble("12.34");
  17. System.out.println(data1);
  18. System.out.println(data2);
  19. }
  20. }
  21. class Student{
  22. String name;
  23. int age;
  24. public Student(String name, int age) {
  25. this.name = name;
  26. this.age = age;
  27. }
  28. @Override
  29. public String toString() {
  30. return "Student{" +
  31. "name='" + name + '\'' +
  32. ", age=" + age +
  33. '}';
  34. }
  35. }

执行结果:

img

2. 大小写转化

String toUpperCase() 转大写
String toLowerCase() 转小写

这两个函数只转换字母。

  1. public static void main(String[] args) {
  2. String s1 = "hello";
  3. String s2 = "HELLO";
  4. // 小写转大写
  5. System.out.println(s1.toUpperCase());
  6. // 大写转小写
  7. System.out.println(s2.toLowerCase());
  8. }

执行结果:

img

3. 字符串和数组的转换

char[ ] toCharArray() 字符串转数组
new String(数组引用) 数组转字符串

  1. public static void main(String[] args) {
  2. String s = "hello";
  3. // 字符串转数组
  4. char[] ch = s.toCharArray();
  5. for (int i = 0; i < ch.length; i++) {
  6. System.out.print(ch[i]);
  7. }
  8. System.out.println();
  9. // 数组转字符串
  10. String s2 = new String(ch);
  11. System.out.println(s2);
  12. }

执行结果:

img

4. 格式化

static String format( );

  1. public static void main(String[] args) {
  2. String s = String.format("%d-%d-%d", 2022, 8, 29);
  3. System.out.println(s);
  4. }

执行结果:

img

四. 字符串替换

使用一个指定的新的字符串替换掉已有的字符串数据,可用的方法如下:


















方法 功能
String replaceAll(String regex, String replacement) 替换所有的指定内容
String replaceFirst(String regex, String replacement) 替换首个指定内容

代码示例:

  • 字符串的替换处理:

    public static void main(String[] args) {

    1. String str = "helloworld" ;
    2. System.out.println(str.replaceAll("l", "_"));
    3. System.out.println(str.replaceFirst("l", "_"));

    }

  • 执行结果:

img

注意事项:

  • 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串.

五. 字符串拆分

可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。

可用方法如下:


















方法 功能
String[] split(String regex) 将字符串全部拆分
String[] split(String regex, int limit) 将字符串以指定的格式,拆分为limit组

如果一个字符串中有多个分隔符,可以用”|”作为连字符.

代码示例:

  • 实现字符串的拆分处理

    public static void main(String[] args) {

    1. String str = "hello world hello rong";
    2. String[] result = str.split(" ") ; // 按照空格拆分
    3. for(String s: result) {
    4. System.out.println(s);
    5. }
    6. System.out.println("==============");
    7. String str1 = "xin&xin=xiang&rong";
    8. String[] str2 = str1.split("&|=");//按照=和&拆分
    9. for(String s: str2) {
    10. System.out.println(s);
    11. }

    }

  • 执行结果:

img

代码示例:

  • 字符串的部分拆分

    public static void main(String[] args) {

    1. String str = "hello world hello rong" ;
    2. String[] result = str.split(" ",2) ;
    3. for(String s: result) {
    4. System.out.println(s);
    5. }

    }

  • 执行结果:

img

有些特殊字符作为分割符可能无法正确切分, 需要加上转义.

  1. 字符”|“,”*“,”+“,”.”都得加上转义字符,前面加上 “ \ “ .
  2. 而如果是 “ \ “ ,那么就得写成 “ \ \ “ ; 使用split来切分字符串时,遇到以反斜杠\作为切分的字符串,split后传入的内容是 \ \ \ \,这么写是因为第一和第三是个斜杠是字符串的转义符。转义后的结果是\ \,split函数解析的不是字符串而是正则,正则表达式中的\ \结果对应\,所以分隔反斜杠的时候要写四个反斜杠。

代码示例:

  • 拆分IP地址

    public static void main(String[] args) {

    1. String str = "192.168.1.1" ;
    2. String[] result = str.split("\\.") ;
    3. for(String s: result) {
    4. System.out.println(s);
    5. }

    }

  • 执行结果:

img

代码中的多次拆分:

  1. ppublic static void main(String[] args) {
  2. //字符串多次拆封
  3. String str = "xin&xin=xiang&rong";
  4. String[] str1 = str.split("&");
  5. for (int i = 0; i < str1.length; i++) {
  6. String[] str2 = str1[i].split("=");
  7. for (String x:str2) {
  8. System.out.println(x);
  9. }
  10. }
  11. String s = "name=zhangsan&age=18" ;
  12. String[] result = s.split("&") ;
  13. for (int i = 0; i < result.length; i++) {
  14. String[] temp = result[i].split("=") ;
  15. System.out.println(temp[0]+" = "+temp[1]);
  16. }
  17. }

执行结果:

img

六. 字符串截取

从一个完整的字符串之中截取出部分内容。可用方法如下 :


















方法 功能
String substring(int beginIndex) 从指定索引截取到结尾
String substring(int beginIndex, int endIndex) 截取部分内容

代码示例:

  1. public static void main(String[] args) {
  2. String str = "helloworld" ;
  3. System.out.println(str.substring(5));
  4. System.out.println(str.substring(0, 5));
  5. }

执行结果:

img

注意事项:

  1. 索引从0开始
  2. 注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标,即(0,4)

七. 其他操作方法

1. String trim()

去掉字符串中的左右空格,保留中间空格

trim 会去掉字符串开头和结尾的空白字符(空格, 换行, 制表符等).

示例代码:

  1. public static void main(String[] args) {
  2. String str = " hello world " ;
  3. System.out.println("["+str+"]");
  4. System.out.println("["+str.trim()+"]");
  5. }

执行结果:

img

2. boolean isEmpty ()

isEmpty() 方法用于判断字符串是否为空

示例代码:

  1. public static void main(String[] args) {
  2. String str = "";
  3. System.out.println(str.isEmpty());
  4. }

执行结果:

img

3. int length()

用于求字符串的长度

示例代码:

  1. public static void main(String[] args) {
  2. String str = "xinxinxiangrong";
  3. System.out.println(str.length());
  4. }

执行结果:

img

4. 判断字符串开头结尾

boolean startsWith(String prefix) 判断字符串是否以某个字符串开头的

boolean endWith(String sufix) 判断字符串是否以某个字符串结尾的

示例代码:

  1. public static void main(String[] args) {
  2. String str = "xinxinxianrong";
  3. System.out.println(str.startsWith("xin"));
  4. System.out.println(str.endsWith("rong"));
  5. }

执行结果:

img

5. boolean contains(String str)

判断字符串中是否包含某个字符串

示例代码:

  1. public static void main(String[] args) {
  2. String str = "xinxinxianrong";
  3. System.out.println(str.contains("inx"));
  4. }

执行结果:

img

发表评论

表情:
评论列表 (有 0 条评论,76人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JavaString

    /\ 接口 接口中只有常量和抽象方法 常量 默认 类型public static final 接口中定义时,写不写都是这样 方法的默认类