字符串查找

从一个完整的字符串之中查找子字符串的存在就属于字符串查找操作,在String类里面提供有如下几个查找方法:

  • public boolean contains​(String s)
    判断此字符串是否存在。
  • public int indexOf​(String str)
    从开头查找字符串的位置
  • public int indexOf​(String str,int fromIndex)
    从指定位置查找字符串的位置
  • public int lastIndexOf​(String str)
    由后向前查找指定字符串位置
  • public int lastIndexOf​(String s,int fromIndex)
    从指定位置由后向前查找指定字符串
  • public boolean startsWith​(String prefix)
    判断是否以指定的字符串开头
  • public boolean startsWith​(String prefix,int toffset)
    由指定位置判断是否以指定的字符串开头
  • public boolean endsWith​(String suffix)
    判断是否已指定字符串结束
class 测试 
{
	public static void main(String[] args) 
	{
		String strA = "hellow";
		String strB = "H";
		System.out.println(strA.contains(strB));
	}
}

在这里插入图片描述此方法的操作相对而言比较直观一些,但是这个方法是从JDK1.5以后开始追加到程序之中的功能,在这之前一般通过indexOf()完成。
范例:

class 测试 
{
	public static void main(String[] args) 
	{
		String strA = "hellow";
		String strB = "H";
		System.out.println(strA.indexOf(strB));
	}
}

在这里插入图片描述结果-1表示在此字符串中没有找到这个字符,如果是不是负数则表示该是字符的索引位置,它是由前向后查找的,也可以由后向前查找 : lastIndexOf()。
范例:

class 测试 
{
	public static void main(String[] args) 
	{
		String strA = "hellow";
		String strB = "w";
		System.out.println(strA.lastIndexOf(strB));
	}
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值