String类方法的列举及练习

String类方法的使用:

**length():测试长度

trim():去掉字符串的前后空格

compareTo():比较第一个字母的数字相减

equalsIgnoreCase():指定对象比较,不考虑大小写

charAt():索引字符串的第几个字符是什么

indexOf():返回一个子串的索引

lastIndexOf():指定索引,从后往前找

substring():截取子串

startsWith():判断前缀后缀

endsWith():判断后缀

toUpperCase():大写

toLowerCase():小写

contains():包含否

valueOf():把各种数据类型转换为字符串的方法**

package cn_tedu_demo;

public class Demo {
	public static void test1(){
		String str =new String();
		byte[] b ={97,98,99};
		String str2 =new String(b);
		System.out.println(str2);//abc
		char[] c ={'1','b'};
		System.out.println(new String(c));//1b
		System.out.println(b);//[B@15db9742
		System.out.println(c);//1b
	}
	//常用方法
	public static void test2(){
		//返回字符串的长度
		System.out.println("hello".length());//5
		//去掉字符串的前后空格
		System.out.println("     he   llo    ".trim());//he   llo
		//equals.hashCode(),toString方法
		//比较第一个字母的数字相减
		System.out.println("abc".compareTo("bcd"));//-1
		//指定对象比较,不考虑大小写
		System.out.println("abc".equalsIgnoreCase("Abc"));//true
		//charAt()
		System.out.println("hello".charAt(2));//l
		//indexof,返回一个子串的索引
		System.out.println("hello".indexOf('e'));//返回索引位置:1
		System.out.println("hello".indexOf("ellw"));//不存在字符串,返回为-1
		System.out.println("hello".indexOf("l"));//2
		//从3开始找
		System.out.println("hello".indexOf("l",3));//3,在第三个的位置上找到
		//lastIndexOf,指定索引,从后往前找
		System.out.println("hello".lastIndexOf("1"));//-1,表示不存在
		System.out.println("hello".lastIndexOf("l",4));//2
		//subString(),截取子串
		System.out.println("hello123".substring(2));//llo123
		//包含索引,不包含[2,4),有2和3
		System.out.println("hello123".substring(2,4));//ll
		//判断前缀后缀
		System.out.println("12345678999".startsWith("123"));//判断前缀是不是123,true
		System.out.println("asdcvg0".endsWith("X"));//判断后缀是不是X,false
		//大小写字符
		System.out.println("aBxc".toUpperCase());//ABXC
		System.out.println("ADBhsmx".toLowerCase());//adbhsmx
		System.out.println("abcde".contains("cd"));//返回true表示包含,否则不包含   true
		//valueOf,把各种数据类型转换为字符串的方法
		System.out.println(String.valueOf(123));//123
		char[] c ="abc".toCharArray();
		
	
		
	}
	public static void main(String[] args) {
		//test1();
		test2();
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值