java中String的某些使用方法

关于java中字符串方法的应用

比较两个字符串是否相等

永远记得我的初中老师和我说过,听会了,并不是真正的学会了。只有把自己学的东西讲给别人听,让别人听懂,才是真的学会了。

比较两个字符串是否相等,使用equals方法。实现代码如下。


public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="abcda";
	    String str2="Abcda";
	    String str3="abcda";
	    System.out.println(str1.equals(str2));
	    System.out.println(str1.equals(str3));
	    		
	}

}
 

运行结果如下,我们可以看出equals方法是区分大小写的。
在这里插入图片描述

忽略差字符大小写的字符串比较方法
public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="abcda";
	    String str2="Abcda";
	    String str3="abcda";
	    System.out.println(str1.equalsIgnoreCase(str2));
	    System.out.println(str1.equalsIgnoreCase(str3));    		
	}
}

运行结果如下图,我们可以看出equalsIgnoreCase方法是去不区别大小写的。
在这里插入图片描述

判段字符串是否为空

判断字符串是否为空值 (非null)

public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="";
		String str2="aa";
	    System.out.println(str1.isEmpty());
	    System.out.println(str2.isEmpty());
	}

}

运行结果如图
在这里插入图片描述

字符串的索引
public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="abvcvdAa";
		String str2="bc";
	    System.out.println(str1.indexOf("a"));       //从头开始查,查询到第一个后就停止向后查询
	    
	    System.out.print("str2字符出现在str1中的位置为");
	    System.out.println(str1.indexOf(str2));
	    
	    System.out.print("当判断的字符不属于查询字串时的值为:");
	    System.out.println(str1.indexOf("h"));      //如果所查字符不再字符串里,返回-1
        
	    System.out.print("从第四个开始,查询后边的a字母的的值为");
	    System.out.println(str1.indexOf("v",3));   //从规定的下标后边查询
	    
	    System.out.println(str1.indexOf(65));// 65为A的Ascll码
	}

}

运行如下图。我们要知道字符串的下标是从0开始的
在这里插入图片描述

求字符串的长度
public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="abvcvdAa";
        System.out.println(str1.length());		//得到字符串str1的长度
     	}

	}

运行如下图
在这里插入图片描述

字符串字符替换
public class test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1="abvcvdAa";
        System.out.println(str1.replace('a', 'g'));		
     	}

	}

输入结果
在这里插入图片描述

判断字符串的开头
public class test {

	public static void main(String[] args) {
     String str="www.daixin.com";
     System.out.println(str.startsWith("www"));//判断是不是以www开头
     System.out.println(str.endsWith("com"));  //判断字符串是不是以com结尾
		
  }
}

运行结果
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值