java字符串常用方法
文章目录
- 将此字符串与指定对象进行比较。
- 返回char指定索引处的值。
- 测试字符串是否以指定后缀结尾
- 测试字符串是否以指定前缀开头
- 判读字符串是否为空
- 求字符串长度
- 指定子字符串的替代
- 字符串拆分
- 返回一个字符串,该字符串是此字符串的子字符串。
- 将此字符串转化为新的字符数组
- String所有字符转换为小写。
- String所有字符转换为大写
- 忽略大小写的比较
- 去掉前导和尾随的空格
将此字符串与指定对象进行比较。
String s1="abc";
String s2="abc";
System.out.println(s1==s2);//true
String s3 = new String("abc");
System.out.println(s1==s3);//false
//boolean equals(Object anObject) 将此字符串与指定对象进行比较。
boolean b1 = s1.equals(s2);
System.out.println(b1);//true
boolean b2 = s1.equals(s3);
System.out.println(b2);//true
返回char指定索引处的值。
//char charAt(int index)
String s4 = "abcdef";
char c1=s4.charAt(1);//b
System.out.println(c1);
测试字符串是否以指定后缀结尾
//boolean endsWitch(String suffix)
String s5 = "2023年6月";
boolean b3 = s5.endsWith("6月");
System.out.println(b3);//true
测试字符串是否以指定前缀开头
//boolean startsWitch(String suffix)
String s6 = "2023年6月";
boolean b4 = s6.startsWith("2023");
System.out.println(b4);//true
判读字符串是否为空
//boolean isEmpty()
String s7 = "";
boolean b5 = s7.isEmpty();
System.out.println(b5); //true
求字符串长度
//int length()
String s8 ="abcdef";
int len=s8.length();
System.out.println(len);//6
指定子字符串的替代
//replace(CharSequence target, CharSequence replacement)
// 子字符串 替代字符串
String massage="你真是TMD";
String s9 = massage.replace("TMD", "***");
System.out.println(s9);//你真是***
字符串拆分
//split (String regex)
String s10="李四,23";
String[] sq1 = s10.split(",");
System.out.println(Arrays.toString(sq1));//[李四,23]
//以逗号来分割字符串,分割完后成为数组
返回一个字符串,该字符串是此字符串的子字符串。
//substring (int beginIndex)
// 索引
String s11 ="abcdef";
String sub1 = s11.substring(1);
//返回从索引1开始的字符串
System.out.println(sub1);//bcdef
//substring(int beginIndex, int endIndex)
// 起始索引 结束索引(取不到)
String s11 ="abcdef";
String sub2 = s11.substring(1, 3);
//最大结束索引要不到
System.out.println(sub2);//bc
将此字符串转化为新的字符数组
//char[] toCharArray()
String s11 ="abcdef";
char[] c2 = s11.toCharArray();
System.out.println(Arrays.toString(c2));//[a, b, c, d, e, f]
String所有字符转换为小写。
//toLowerCase()
String s12="ABCDEF";
String sl = s12.toLowerCase();
System.out.println(sl);//abcdef
String所有字符转换为大写
toUpperCase()
//toUpperCase()
String s13="abcdef";
String st = s13.toUpperCase();
System.out.println(st);//ABCDEF
忽略大小写的比较
//equalsIgnoreCase(String anotherString)
String s12="ABCDEF";
String s13="abcdef";
boolean b = s12.equalsIgnoreCase(s13);
System.out.println(b);//true
去掉前导和尾随的空格
//String trim()
String s14=" abcdef ";
System.out.println(s14);
String tm = s14.trim();
System.out.println(tm);
//abcdef
学的不是技术,更是梦想!!!
还没有评论,来说两句吧...