Java中String类的一些常用方法归纳

/**
 * 在这个类中讨论关于String这个类的特点
 * @author issac
 *
 */
public class Test02String {
	public static void main(String[] args) {
		String str1 = new String("abc");
		String str2 = new String("abc");
		// == 对对象的引用地址进行比较
		//String类对equals进行了重写,此时equals方法的比较过程是:
		//	1、使用==比较两个对象是否是同一个对象
		//	2、对String对象的字面进行比较,如果都一样,返回true
		
		System.out.println("==:"+(str1 == str2));
		System.out.println("equals:"+str1.equals(str2));
		
		String s3 = "abc";
		String s4 = "abc";
		System.out.println("==:"+(s3 == s4));
		
		char[] c = {'a','b','c'};
		String s5 = new String(c);
		System.out.println(s5);
		
		byte[] b = {97,98,99};
		String s6 = new String(b);
		System.out.println(s6);
		
		System.out.println("==================");
		/**
		 * String类中常用的方法
		 */
		
		String str = "abcdefggfedcba";
		
		//1、charAt -- 返回的指定索引处的char值 返回值类型:char
		//	Java中索引值是从0开始
		//StringIndexOutOfBoundsException --数组下标索引越界
		System.out.println(str.charAt(2));//c
		
		//2、indexOf (有多个重载的方法) 可用于查找字符串第一次出现的位置
		// 		-1 表示没有找到
		System.out.println(str.indexOf("12"));
		
		//3、lastIndexOf(有多个重载的方法) 可用于查找字符串中最后一次出现的索引
		System.out.println(str.lastIndexOf("g"));
		
		//4、toLowerCase() -- 将大写字符转成小写字符
		//5、toUpperCase() -- 将小写字符转成大写字符
		String s7 = "AbCdEf";
		System.out.println(s7.toLowerCase());
		System.out.println(s7.toUpperCase());
		
		//6、comepareTo(str) --按照字典顺序比较两个字符串的大小
		//	返回值类型:
		//		若参数字符串按照字典顺序(Unicode表)等于此字符串,返回0
		//		若参数字符串按照字典顺序(Unicode表)小于此字符串,返回一个小于0的数
		//		若参数字符串按照字典顺序(Unicode表)大于此字符串,返回一个大于0的数
		//		
		System.out.println("123".compareTo("111"));
		
		//6、replace(被替换字符,替换字符)
		String s7_1 = s7.replace('b', '我');
		System.out.println(s7_1);
		
		//7、split --根据给定的正则表达式的匹配拆分字符串
		//当我们要用"."的时候,需要用到转义的写法 --"\\."
		String ip = "192.168.1.1";
		String[] ips = ip.split("\\.");
		System.out.println(ips.length);
		for (int i = 0; i < ips.length; i++) {
			System.out.println(ips[i]);
		}
		
		//8、subString -- 截取  包上不包下
		//	第一个参数: 截取的起始位置
		//	第二个参数:截取的结束位置
		String s7_2 = s7.substring(2, 4);//s7:AbCdEf
		System.out.println(s7_2);//Cd
		
		//9、startWith/endWith -- 判断字符串是否以"..."开头或者结尾,返回值:boolean
		
		//10、equalsIgnoreCase -- 将两个字符串进行比较,不考虑大小写
		//常用于:验证码
		System.out.println("AbcdEf".equalsIgnoreCase("abcdef"));
		
		
		//11、trim -- 去除给定字符串开头的空格
		String s8 = "             f a s d f";
		System.out.println(s8);
		System.out.println(s8.trim());
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值