滴滴~ 虽然在CSDN已有些岁月 但都是以老6的形式存在 平时有打笔记的习惯 以后会向家分享一些自己的微薄弱知识 不足之处 还望诸佬指点
前言
我们在学校学习或者在工作中都避免不了string类的使用 那么常用的方法 我大概整理了一些 分享一下
提示:以下是本篇文章正文内容,下面案例可供参考
①substring
String str="我爱你中国 ";
System.out.println(str.substring(0,2)); //我爱
System.out.println(str.substring(1)); //爱你中国
第一个参数是截取的起始下标 到下标为2 但不包括下标为2的内容
若只指明起始下标 则默认截取后面剩余的 全部内容
②length()
String str="我爱你中国";
System.out.println(str.length()); //5
此方法是获取字符串的长度
③trim()
String str="hello world ";
System.out.println(str.trim()); //hello world
trim()方法去除掉字符串左右两侧的空格 但不会去除掉中间部分的空格
④replace()
String str = "我爱你中国";
System.out.println(str.replace("爱","挺"));//我挺你中国
replace()方法第一个参数为旧的内容 第二个参数为替换的新的内容
⑤indexOf()
String str = "我爱你中国";
System.out.println("第一个爱字的下标为"+str.indexOf("爱"));//1
indexOf()返回指定字符串的第一个的下标 lastIndexOf()同理
⑥toUpperCase()
String str="hello world";
System.out.println(str.toUpperCase()); //HELLO WORLD
toUpperCase()方法 是将小写字母转为大写
⑦toLowerCase()
String str="HELLO WORLD";
System.out.println(str.toLowerCase()); //hello world
toLowerCase()方法 是将大写字母转为小写
⑧contains()
String str="hello world";
System.out.println(str.contains("h"));//true
System.out.println(str.contains("s"));//false
contains()方法 判断该字符串是否包含指定的字段 包含返回true 则返回 false
⑨isEmpty()
String str="hello world";
System.out.println(str.isEmpty()); //false
isEmpty()方法 用于判断字符串是否为空
⭐⭐对String类中的方法就记录到此为止了,欢迎大家补充⭐⭐