AP计算机科学A自学笔记:String类(2)

这篇博客探讨了Java中的String类,重点在于如何比较String对象。讲解了equals方法和compareTo方法的区别,强调了不应使用'=='来比较String的内容。此外,还介绍了length()、substring()和indexOf()等String类的常用方法及其用法。
摘要由CSDN通过智能技术生成

比较String对象
有两种方法比较String对象:
1使用String类覆盖的Object类的equals方法,返回true如果两个String对象字符串相同,否则返回false

if (string1.equals(string2))

2使用compareTo方法,compareTo方法把string按照ASCII表的顺序逐字符比较,ASCII表中数字顺序先于大写字母,大写字母先于小写字母。
compareTo比较时如果两个字符串的字符不相同,返回第一个不相同字符ASCII差值,如果字符相同但是长度不同返回长度差值,如果字符和长度相同返回0.

package standardClasses;

public class ComparisonOfString {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String s1 = "HOT";
		String s2 = "HOTEL";
		String s3 = "GOT";
		String s4 = "HOT";
		System.out.println(s1.compareTo(s2));
		System.out.println(s1.compareTo(s3));
		System.out.println(s1.compareTo(s4));
	}

}

如果使用==比较string会判断两个指针是否指代同一字符串对象,而非比较字符串的实际内容。

String s1 = "abc";
String s2 = "abc";
if (s1 == s2) {
}

会返回true,因为为了节约内存,介于String对象不可修改的性质,对于同一字符串内容java只会创建一个字符串对象,因而s1和s2指代其实相同

String s1 = "abc";
String s2 = new String("abc");
if (s1 == s2)

会返回false,因为s2此时是新建的字符串对象,和s1指代不同。
因此,尽量避免使用==比较string

其他String方法:
int length()
返回String长度

String substring(int startIndex)
返回该String一部分的新字符串,子字符串从startIndex位置字符到字符串末尾。如果startIndex为负或者大于String长度会抛出异常IndexOutOfBoundsException

String substring(int startIndex, int endIndex)
返回String一部分的子字符串,子字符串从startIndex开始,到endIndex - 1. (可以理解startIndex是第一个要截的字符,endIndex是第一个不要截的字符)。如果startIndex小于0,endIndex大于String长度,或者startIndex大于endIndex会抛出IndexOutOfBoundsException

int indexOf (String, str)
返回该字符串中第一次出现str的索引,如果不存在返回-1。如果str为null返回NullPointerException

实例程序

	System.out.println("unhappy".substring(2));
		System.out.println("cold".substring(4));
		try {
			System.out.println("cold".substring(5));
		} catch (StringIndexOutOfBoundsException exception) {
			System.out.println("Index out of bounds");
		}
		System.out.println("strawberry".substring(5, 7));
		String c = "crayfish";
		System.out.println(c.substring(4, 8));
		try {
			System.out.println(c.substring(4, 9));
			System.out.println(c.substring(5, 4));
		} catch (StringIndexOutOfBoundsException exception) {
			System.out.println("Index out of bounds");
		}
			
		
		String s = "funnyfarm";
		System.out.println(s.indexOf("farm"));
		System.out.println(s.indexOf("farmer"));
		System.out.println(s.length());

try……catch语句AP完全不会涉及,这里是我自己为了显示结果加上去的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值