String类常用方法

发布于2020-09-02   682 次阅读


本文最后更新于2022年6月1日,已超过 1 年没更新!内容可能已失效,请自行测试。

JavaDoc文档简介

进行开发的过程中,需要大量使用Java的API文档,这个文档可以在线查看

https://docs.oracle.com/javase/9/docs/api/overview-summary.html

JDK1.9之前,常用类库会在JVM启动时全部加载;从1.9开始提供模块化设计,将一些程序类放在了不同的模块里

字符串与字符数组

案例代码:字符串与字符数组的转换
/*字符串与字符数组的转换*/
public class StringCharDemo {
  public static void main(String[] args) {
    String str2 = "hellowworld";
    char[] result = str2.toCharArray(); // 将字符串变成字符数组
    for (int x = 0; x < result.length; x++) {
      result[x] -= 32;
    } // 全部变成大写
    String newStr = new String(result); // 字符数组转换为String类
    System.out.println(newStr); // 输出
  }
}
案例代码:判断一个字符串中的数组是否全由数字组成
/**
 * 判断一个字符串中的数组是否全由数字组成 如果想要判断字符串中的每一位数据,最好将其转换为字符数组 可以判断每一个字符是否在数字的范围之内 ('0'~'9') 如果有一位不是数字,那么验证失败
 */
public class StringCharDemo2 {
  public static void main(String[] args) {
    /** 定义两个字符串 */
    String str = "123456";
    String str2 = "123hh456";
    if (isAllnum(str)) {
      System.out.println("全是数字组成");
    } else {
      System.out.println("不全是数字组成");
    }

    if (isAllnum(str2)) {
      System.out.println("全是数字组成");
    } else {
      System.out.println("不全是数字组成");
    }
  }
  // 写一个用于判断的方法
  public static boolean isAllnum(String str) {
    char[] c = str.toCharArray();
    boolean flag = true;
    for (int i = 0; i < c.length; i++) {
      if (c[i] < '0' || c[i] > '9') {
        flag = false;
      }
    }
    return flag;
  }
}

字符串与字节数组

字符串和字节数组之间也可以实现转换的操作,当进行转换时,主要是为了进行二进制的数据传输或者编码转换

方法名称类型作用
public String(byte[] bytes)构造将全部的字节数组转换为字符串
public String(byte[] bytes,int offset,int length)构造将部分的字节数组转换为字符串
public byte[] getBytes()普通将字符串转为字节数组
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException普通编码转换
字符串与字节数组
案例代码:字符串与字节转换
/*字符串与字节转换 */
public class StringByteDemo {
  public static void main(String[] args) {
    String str = "helloworld";
    byte[] bb = str.getBytes(); // 将字符串变为字节数组
    for (int i = 0; i < bb.length; i++) {
      bb[i] -= 32;
    }
    System.out.println(new String(bb));
    System.out.println(new String(bb, 0, 5));
  }
}

字符串比较

方法名称类型作用
public boolean equals(String anObject)普通区分大小写的相等比较
public boolean equalsIgnoreCase(String anObject)普通不区分大小写的相等比较
public int compareTo(String anotherString)普通进行字符串大小比较,返回一个int数据:大于,小于,等于
public int compareToIgnoreCase(String str)普通不区分大小写进行字符串大小比较
字符串比较相关方法
案例代码:字符串比较
/*字符串比较 */
public class StringEqualsDemo {
  public static void main(String[] args) {
    String strA = "AB";
    String strB = "Ab";
    String strC = "6";
    String strD = "5";
    System.out.println(strA.equals(strB)); // 区分大小写的相等比较
    System.out.println(strA.equalsIgnoreCase(strB)); // 不区分大小写的相等比较
    System.out.println(strC.compareTo(strD)); // 进行字符串大小比较
    System.out.println("HELLO".compareTo("HELLO")); // 进行字符串大小比较
    System.out.println(strD.compareToIgnoreCase(strC)); // 不区分大小写进行字符串大小比较
  }
}

字符串查找

从一个完整的字符串中查找某一个字符,返回其索引位置

方法名称类型作用
public boolean contains(String s)普通判断字符串是否存在
public int indexOf(String s)普通从头查找指定字符串的位置
public int indexOf(int ch, int fromIndex)普通从指定位置查找指定字符串的位置
public int lastIndexOf(String s)普通由后向前查找指定字符串的位置
public int lastIndexOf(String s, int fromIndex)普通从指定位置由后向前查找指定字符串的位置
public  startsWith(String prefix)普通判断是否以指定的字符串开头
public startsWith(String prefix, int toffset)普通由指定位置判断是否以指定的字符串开头
public boolean endsWith(String suffix)普通判断是否以指定的字符串结尾
字符串查找相关方法
案例代码:判断字符串是否存在
/*判断字符串是否存在*/
public class StringFindDemo {
  public static void main(String[] args) {
    String str = "helloworld";
    System.out.println(str.contains("hello"));
  }
}
判断字符串是否存在2
/*判断字符串是否存在2*/
public class StringFindDemo2 {
  public static void main(String[] args) {
    String str = "helloworld";
    System.out.println(str.indexOf("hello")); // 0 代表第0个位置
    System.out.println(str.lastIndexOf("0")); // 6代表第6个位置
  }
}

indexOf是为了进行字符串位置的查询,在一些开发中可以利用此进行索引的查找,也可以使用lastIndexOf由后往前查找

判断是否以指定的字符串开头
/*判断是否以指定的字符串开头 */
public class StringFindDemo3 {
  public static void main(String[] args) {
    String str = "helloworld";
    System.out.println(str.startsWith("h"));
    System.out.println(str.endsWith("d"));
  }
}

字符串替换

方法名称类型作用
public String replaceFirst(String regex, String replacement)普通替换首个
public String replaceAll(String regex, String replacement)普通全部替换
字符串替换相关方法
案例代码:字符串替换
/*案例代码:字符串替换*/
public class StringRepDemo {
  public static void main(String[] args) {
    String str = "helloworld";
    System.out.println(str.replaceAll("l", "_"));
    System.out.println(str.replaceFirst("l", "_"));
  }
}

字符串拆分

普通方法名称类型作用
public String[] split(String regex)普通按照指定的字符串进行拆分
public String[] split(String regex, int limit)按照指定的字符串进行拆分,限制个数
字符串拆分相关方法
案例代码:字符串拆分
/*案例代码:字符串拆分 */
public class StringSplDemo {
  public static void main(String[] args) {
    String str = "hello world hello moto";
    String str2 = "hello world hello moto";
    String[] result = str.split(" ");
    for (int i = 0; i < result.length; i++) {
      System.out.println(result[i]);
    }
    System.out.println("--------------");
    String[] result2 = str2.split(" ", 2);
    for (int i = 0; i < result2.length; i++) {
      System.out.println(result2[i]);
    }
  }
}

字符串截取

方法名称类型作用
public String substring(int beginIndex)普通从指定索引截取到结尾
public String substring(int beginIndex, int endIndex)普通截取指定范围内的字符串
字符串截取相关方法
案例代码:字符串截取
/*案例代码:字符串截取 */
public class StringSubDemo {
  public static void main(String[] args) {
    String str = "HelloWorld!";
    System.out.println(str.substring(3)); // 从第三个位置开始截取到末尾
    System.out.println(str.substring(0, 5)); // 只截取第0到第5个位置的字符串
    System.out.println("----------------");
    String str2 = "yeyufan-photo-张三.jpg"; // 字符串结构:"用户-photo-姓名.后缀"
    int beginIndex = str2.indexOf("-", str2.indexOf("photo")) + 1;
    int endndex = str2.lastIndexOf(".");
    System.out.println(str2.substring(beginIndex, endndex));
  }
}

字符串格式化

方法名称类型作用
public static String format(String format, 各种类型)普通根据指定的结构进行文本格式化显示
字符串格式化相关方法
案例代码:字符串格式化
/*案例代码:字符串格式化 */
public class StringForDemo {
  public static void main(String[] args) {
    String name = "张三";
    int age = 18;
    double score = 98.765321;
    String str = String.format("姓名:%s,年龄:%d,成绩:%5.2f", name, age, score);
    System.out.println(str);
  }
}

其他操作方法

普通方法名称类型作用
public String concat(String str)普通字符串连接
public String intern()普通字符串入池
public boolean isEmpty()普通判断是否为空
public int length()普通计算字符串长度
public String trim()普通去除左右的空格
public String toUpperCase()普通转换为大写
public String toLowerCase()普通转换为小写
字符串的其他操作方法
案例代码:字符串连接
/*案例代码:字符串连接 */
public class StringConDemo {
  public static void main(String[] args) {
    String strA = "yeyufan.cn";
    String strB = "ye".concat("yufan").concat(".cn");
    System.out.println(strA);
    System.out.println(strB);
    System.out.println(strA == strB);
  }
}
案例代码:字符串入池
/*案例代码:字符串入池*/
public class StringInternDemo {
  public static void main(String[] args) {
    String str1 = "a";
    String str2 = "b";
    String str3 = "ab";
    String str4 = str1 + str2;
    String str5 = new String("ab");

    /*这个结果为true.
    因为字符串的值的内容相同 */
    System.out.println(str5.equals(str3));
    /*对比的是引用的地址是否相同.
    由于str5采用new String方式定义的,所以地址引用一定不相等,所以结果为false. */
    System.out.println(str5 == str3);
    /*当str5调用intern的时候,会检查字符串池中是否含有该字符串.
    由于之前定义的str3已经进入字符串池中,所以会得到相同的引用. */
    System.out.println(str5.intern() == str3);
    /*采用new创建的字符串对象不进入字符串池
    字符串相加的时候,都是静态字符串的结果会添加到字符串池,如果其中含有变量则不会进入字符串池中*/
    System.out.println(str5.intern() == str4);
  }
}
案例代码:字符串连接
/*案例代码:字符串连接 */
public class StringConDemo {
  public static void main(String[] args) {
    String strA = "yeyufan.cn";
    String strB = "ye".concat("yufan").concat(".cn");
    System.out.println(strA);
    System.out.println(strB);
    System.out.println(strA == strB);
  }
}
案例代码:字符串判断是否为空
/*案例代码:字符串判断是否为空*/
public class StringEmptyDemo {
  public static void main(String[] args) {
    String str = "";
    System.out.println(str.isEmpty());
    System.out.println("yeyufan".isEmpty());
    /*null和""不是一个概念,一个表示无实例化对象,一个表示内容为空.判断字符串是否为空是在有实例化对象的前提下进行的*/
  }
}
案例代码:计算字符串长度
/*计算字符串长度*/
public class StringLengthDemo {
  public static void main(String[] args) {
    String str = "我的长度是6";
    System.out.println("字符串长度为:" + str.length());
  }
}
案例代码:去除左右的空格
/*去除左右的空格*/
public class StringTrimDemo {
  public static void main(String[] args) {
    String str = " ABCD ";
    System.out.println(str);
    System.out.println(str.trim());
  }
}
案例代码:字符串大小写转换
/*案例代码:字符串大小写转换*/
public class StringUppDemo {
  public static void main(String[] args) {
    String str = "hello world!!";
    System.out.println(str.toUpperCase());
    System.out.println(str.toUpperCase().toLowerCase());
  }
}
案例代码:实现首字母大写
/*案例代码:实现首字母大写*/
public class StringUpperDemo {
  public static void main(String[] args) {
    String str = "dasdaddd";
    System.out.println(Upper(str));
  }

  public static String Upper(String s) {
    if (s == null || "".equals(s)) {
      return s;
    }
    if (s.length() == 1) {
      return s.toUpperCase();
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1);
  }
}

=

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。