String类

时间:2025-02-21 17:40:15
public static void main(String[] args) throws UnsupportedEncodingException { String str = "你要悄悄学python惊艳所以人! pythonNB.mp4"; //使用字符串api来处理字符串 //1. 获得长度 length():int System.out.println( str.length() ); //2. 获得指定下标处的字符 charAt(int index):char System.out.println( str.charAt(1) ); //3. 查看字符串中时候包含 指定字符串内容 contains(String str):boolean System.out.println( str.contains("python") ); //4.把字符串转出字符数组 toCharArray():char[] char[] chs= str.toCharArray(); System.out.println( Arrays.toString(chs) ); //5. 查询指定字符串的首次出现的下标 indexOf(String str):int System.out.println( str.indexOf("py") ); // 从指定位置后查找 System.out.println( str.indexOf("py", 8)); // 反向查找 System.out.println( str.lastIndexOf("py") ); // 反向查找,从指定位置前 System.out.println( str.lastIndexOf("py", 18) ); //6 去除字符串两端的空格 trim():String System.out.println(str.trim() ); //7 把小写转成大写 toUpperCase():String System.out.println( str.toUpperCase() ); //8 大写转小写 toLowerCase():String System.out.println( str.toLowerCase() ); //9 判断字符串是否以某个字符串结尾 endsWith( String s ):boolean System.out.println( str.endsWith( "mp4" ) ); //10 判断字符串是否以 某个字符串开始 startsWith(String s):boolean System.out.println( str.startsWith("你") ); //11.替换字符 replace(char oldChar, char newChar):String System.out.println( str.replace('你', '我') ); // replace(String str, String str2):String System.out.println( str.replace("python", "java") ); String ss = "abcdefg12mly3s5"; //正则:用一个模式去匹配字符串是否符合这个规则 replaceAll(String reg, String newStr):String System.out.println( ss.replaceAll("[a-z]", "*") ); //13 字符串拆分 split(String reg):String[] String mm = "刘德华,歌手,50,香港"; String[] info = mm.split(","); System.out.println( info[0] ); // 14 字符串截取 System.out.println( str.substring(5) ); System.out.println( str.substring(5, 10)); // 15 字符串编码解码问题【防止乱码编码一致】 String dd = "奥利给"; byte[] bs = dd.getBytes();//[-80, -62, -64, -5, -72, -8] byte[] bs = dd.getBytes("UTF-8");//[-27, -91, -91, -27, -120, -87, -25, -69, -103] System.out.println(Arrays.toString(bs) ); //编码 byte[] bbs = {-27, -91, -91, -27, -120, -87, -25, -69, -103}; String sss = new String(bbs, "utf-8"); }