首页 > 其他 > 详细

获取字符串信息

时间:2021-02-23 13:36:52      阅读:16      评论:0      收藏:0      [点我收藏+]

 

length()——获取字符串长度

1.  String str = "good good study";
2.  int size = str.length();   //size=15

indexOf(String s)——获取字符串s在指定字符串中首次出现的索引位置,不存在返回-1
lastIndexOf(String s)——获取字符串s在指定字符串中最后出现的索引位置,不存在返回-1

1.  String str = "good good study";
2.  int index = str.indexOf("g");  //index=0;字符串下标为0~length()-1
3.  int lastIndex = str.lastIndexOf("g");  //lastIndex=5

charAt(int index)——获取指定索引处的字符

1.  String str = "good good study";
2.  char c = str.charAt(5);   //c = ‘g‘

substring(int index)——获取从指定索引位置到字符串结尾的子串
substring(int beginIndexint endIndex)——获取从指定索引位置到另一指定索引位置结束的子串(不包括结束位置)

1.  String str = "Hello Word";
2.  String substr = str.substring(3)   //substr = "lo Word";
3.  substr = str.substring(0,3)  //substr = "Hel"

trim()——去除前导与尾部的空格

1.  String str = "  Hello Word  ";
2.  str = str.trim();  // str = "Hello Word"

replace()——将指定的字符或字符串替换成新的字符或字符串

1.  String str = "Hello Word";
2.  String newstr = str.("H","h");  //newstr = "hello Word";

startsWith()——判断当前字符串对象的前缀是否为参数指定的字符串
endsWith()——判断当前字符串对象是否以参数指定的字符串结尾

1.  String num = "123456";
2.  boolean b = num.startsWith("123");  //true
3.  boolean b = num.startsWith("456");  //false
4.  boolean b = num.endsWith("456");   //true

equals()——比较字符串(String重写了默认的equals(),所以比较内容不是比较引用,区分大小写)
equalsIgnoreCase()——比较字符串,不区分大小写

1.  String s1 = "abc";
2.  String s2= "abc";
3.  String s3 = "Abc";
4.  boolean b = s1.equals(s2);  //true
5.  boolean b = s1.equals(s3);  //false
6.  boolean b = s1.equalsIgnoreCase(s3);  //true

compareTo()——按字典顺序比较二个字符串

1.  String s1 = "a";
2.  String s2 = "b";
3.  //s1.compareTo(s2)返回-1s2.compareTo(s1)返回1

toLowerCase()——将字符串中的所有字符从大写字母改写为小写字母
toUpperCase()——将字符串中的所有字符从小写字母改写为大写字母
split()——使字符串按指定的字符或字符串对内容进行分割,将结果存放在字符数组中

1.  String str = "192.168.0.0";
2.  String[] newstr = str.split("\\.")  //按照“.”分割,使用转义字符“\\”
3.  String[] newstr2 = str.split("\\."2)  //按照“.”分割,限定分割2
4.  //结果为newstr:[192][168][0][1]newstr2:[192][168.0.1]

StringBuilder 或者 stringBuffer reverse() ——实现字符串的反转

1.  StringBuffer stringBuffer = new StringBuffer();
2.  stringBuffer.append("abcdefg");
3.  System.out.println(stringBuffer.reverse()); // gfedcba

获取字符串信息

原文:https://www.cnblogs.com/libingyan8/p/14435184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!