ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Java String函数

2026/8/22 10:05:35 拓冰建站 浏览量
Java String函数 1.长度length()String s hello; int n s.length(); System.out.println(n);//5用来获取字符串的长度。这里要注意获取字符串、数组、集合的长度的函数有区别的。s.length(); //String 字符串 arr.length; //数组 list.size(); //ArrayList 集合2.获取某个字符charAt()String s hello; char c s.charAt(1); Systen.out.println(c); //e下标从0开始。3.字符串转字符数组toCharArray()String s hello; char[] arr s.toCharArray();得到[h,e,l,l,o]数组。4.截取字符串substring()String s abcdef; string x s.substring(2); Systen.oout.println(x);其中2的意思为从下标2开始截到结尾即结果为cdef。String s abcdef; string x s.substring(1,4);意思为从下标1开始截到下标4。但是要注意结果中包含下标1但不包含下标4可理解为[1,4)即结果为bcd;5.判断字符串是否相等equals()String a hello; string b hello; if(a.equals(b)){ System.out.println(相等); }输出相等注意不可以用比较字符串内容。//判断字符串内容 a.equals(b); //如果忽略大小写 a.equalsIgnoreCase(b); //例如 Hello.equalsIgnoreCase(hello); //结果 trueequals()是严格的内容比较而equalsIgnoreCase()忽略大小写6.查找字符串indexOf()String s sadbutsad; int index s.indexOf(sad); System.out.println(index);返回第一次出现的位置找不到返回-1。所以输出0也可以用来找字符。String s hello; s.indexOf(l);//27.查找最后一次出现lastIndexOf()String s hello; int index s.lastIndexOf(l); System.out.println(index);输出3因为最后一次字母l最后一次出现的下标是3。8.判断是否包含contains()String s hello world; boolean result s.contains(world);结果true。可以理解为world是否是s的字串。9.判断开头startWith()String s hello; s.startWith(he);结果true。10.判断结尾endWith()String s helo.java; s.endWith(.java);结果true。在判断文件后缀中很常见。11.替换replace()String s hello; String result s.replace(l,x); System.out.println(result);得到hexxo;也可以替换字符串String s hello world; String result s.replace(world,java);得到hello java。12.分割split()String s java,python,c; String[] arr s.split(,);得到arr[0] java arr[1] python arr[0] c。注意有些特殊字符如. * ? | ( ) [ ] { } ^ $ \要转义例如String s a.b.c; String[] arr s.split(\\.);13.去掉首尾空白trim()/strip()String s hello ; String result s.trim();结果hello。strip()对Unicode空白字符的处理更完整刷算法题一般使用s.trim()即可。14.判断空字符串isEmpty()String s ; s.isEmpty();结果true。等同于s.length()0官方定义就是长度为0时返回true。15.大小写转换toLowCase()/toUppercase()String s Hello; s.toLowCase();得到hello。相反s.toUpperCase();得到HELLO。总结// 长度 s.length(); // 获取字符 s.charAt(i); // 转字符数组 char[] arr s.toCharArray(); // 截取 s.substring(begin); s.substring(begin, end); // 比较 s.equals(t); // 查找 s.indexOf(abc); s.lastIndexOf(abc); // 判断包含 s.contains(abc); // 开头结尾 s.startsWith(a); s.endsWith(z); // 替换 s.replace(a, b); // 分割 String[] arr s.split(,); // 去空格 s.trim(); // 判断空 s.isEmpty(); // 大小写 s.toLowerCase(); s.toUpperCase();