Java第一阶段(11)【 Java String类、String类中常用的一些方法 】 11.20

版权声明:本文为 欧皇柯基 原创文章,非商用自由转载-保持署名-注明出处, https://blog.csdn.net/qq_42829628/article/details/84308233

API

  • 编写代码时,我们会遇到各种各样的方法需要调用,但是又记不住那么多,这时候就要查询API。
  • API方法钱有个 “已过时”,说明此方法可以用,但不建议使用,有的方法有可替代的方法或者有bug
  • API下载百度上很多,或者评论找我拿都可以

String类

  • String() 空参 创建出来的是一个空串
  • 字符串本质实际上就是字符的数组 char[]
    • String(char[] value)
    char[] arr  = {'H','E','L','L','O'}
    String s1 = new String(arr);
    System.out.println(s1);//输出hello
    

String类中一些常用的方法

字符串的所有操作都通过方法

String 通常叫做字符串常量:调用任何方法,如果返回出新的字符串,原字符串不会发生改变

(拓展)StringBuffer 和 StringBuiler 叫做字符串变量:调用任何方法,如果返回新的字符串,原字符串会发生改变

  • charAt(int index):取到index角标的字符
String a = "abcdefg";
  	char c = a.charAt(3);//取 a 的第三个角标
  	System.out.println(c);//输出:d
  • s.length():获取字符串的长度
String a = "abcdefg";
  	int i = a.length();
  	System.out.println(i);//输出:7
  	char c = a.charAt(a.length()-1);//获取字符串最后一个字符
  	System.out.println(c);//输出 g
  • endsWith(String a ) 测试字符串是否以某个后缀结束
    此方法可以判断文件的类型
String fileName = "123.jpg";
  	if(fileName.endsWith(".jpg") || fileName.endsWith(".m4a") ){
  		System.out.println("是一个音乐文件或图片");//输出 :是一个音乐文件或图片
  	}
  • startWith(String a ) 测试字符串是否以某个前缀开始
String phone = "1350004566";
  	if(phone.startsWith("135")){
  		System.out.println("135开头");//输出:135开头
  	}
  • toUpperCase() 将字符串全部转大写
    toLowerCase() 将字符串全部转小写
String s22 = s2.toUpperCase();
  	String s222 = s2.toLowerCase();
  	System.out.println("大写:" + s22);
  	System.out.println("小写:" + s222);
  • equalsIgnoreCase(String a) 不考虑大小写
    注意:equals严格区分
String a = "abC";
  	String b = "Abc";
  	boolean bool = a.equalsIgnoreCase(b);
  	System.out.println(bool);//输出:true
  • 字符串的截取
    substring(int beginIndex) 从beginIndex开始获取字符到结束
    substring(int beginIndex,int endIndex) 从beginIndex角标开始获取字符到endIndex角标(endIndex角标的值获取不到)
String a = "abcdefg";
  	String b = "abcdefg";
  	String p1 = a.substring(3);//从3角标到最后
  	String p2 = b.substring(3, 6); //[3,6)
  	System.out.println(p1);//defg
  	System.out.println(p2);//def
  • split(String regex) 字符串的切割
    得到String[]
    & # / 都可以作为切割符
    注意: . 符号不能进行切割
String msg = "10001&13&张三";//解析信息-切割 -- &分隔符
  	String[] sarr = msg.split("&");
  	//遍历输出
  	for (int i = 0; i < sarr.length; i++) {
  		System.out.println(sarr[i]);
  	}

猜你喜欢

转载自blog.csdn.net/qq_42829628/article/details/84308233