Java String的一些常用方法

本文详细介绍了Java中String类的多个核心方法,包括charAt、concat、contains、startsWith、endsWith、equals、equalsIgnoreCase、indexOf、lastIndexOf及length等,通过实例展示了这些方法的功能和使用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
		String str = new String("ABCDEFG");
		// 1: char charAt(int index) 返回指定index处的char值
		char a = str.charAt(0);
		// System.out.println(a);
		// 2: String concat(String str)将指定的字符串str连接到当前字符串的末尾,并返回此新字符串对象
		str.concat("H");
		// System.out.println(str);
		// 3: boolean contains(CharSequence s)此字符串对象是否包含指定的字符序列(一般可以认
		// 为是字符串)
		boolean bool = str.contains("AB");
		// System.out.println(bool);
		// 4: boolean startsWith(String prefix)此字符串是否以指定的前缀开头
		boolean bool2 = str.startsWith("AB");
		// System.out.println(bool2);
		// 5: boolean endsWith(String suffx) 此字符串是否以指定的后缀结尾
		boolean bool3 = str.endsWith("AB");
		// System.out.println(bool3);
		// 6: boolean equals(Object anObject)对比此字符串对象与指定对象的内容进行比对
		boolean bool4 = str.equals("abcdefgh");
		// System.out.println(bool4);
		// 7: boolean equalslgnoreCase(String anotherString)对比此字符串对象与指定内容进行忽略
		// 大小写的比对
		boolean bool5 = str.equalsIgnoreCase("abcdefgh");
		// System.out.println(bool5);
		// 8: int indexOf(int ch)返回指定字符在字符串对象中首次出现的索引
		int index = str.indexOf(1);
		// System.out.println(index);
		// 9: int indexOf(String str) 返回指定字符串在字符串对象中首次出现的索引
		int index2 = str.indexOf("C");
		// System.out.println(index2);
		// 10: int lastIndexOf(int ch)返回指定字符在字符串对象中最后一次出现的索引
		int index3 = str.lastIndexOf(3);
		// System.out.println(index3);
		// 11: int lastIndexOf(String str)返回指定字符串在字符串对象中最后- -次出现的索引
		int index4 = str.lastIndexOf("D");
		// System.out.println(index4);
		// int length()返回字符串的长度
		int length = str.length();
		// System.out.println(length);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值