String类对象的创建使用,雇员对象的操作

本文介绍了Java中字符串(String)类的基本使用方法,包括如何获取字符、比较字符串以及连接字符串等常见操作。此外,还展示了如何自定义一个方法来统计指定字符串在目标字符串中出现的次数。

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

public class StringDemo{
	
	public static void main(String[] args){
		
		//类中每一个看来会修改String值得方法,其实都是创建新的String对象(包含修改后的字符串内容)
		//"abcd"+"e"="abcde",看起来没变,其实内存中又开辟了新的内存空间
		
		//String的只读特效带来效率优化可能
		//字符串字面值存储于字符串池,避免反复生成重复的字符串实例
		
		//系统对String的非修改处理效率很高,远远超过了另外两个字符串类StringBuffer和StringBuilder(后续讲解)
		//假设相对字符串频繁的修改最好用后面两个类。
		
		String content="Hello,My Friend,You are my best friend";
		System.out.println(content.charAt(2));
		System.out.println(content.compareTo("hello"));
		content=content.concat("I lied");
		System.out.println(content);
		
		
	}
	
}


public class Employee{

	public String name;
	public int age;
	
	//返回个人信息
	public String toString(){
	
		return "我的名字叫:"+name+",今年:"+age+"岁";
	
	}
	//在制定的字符串中查找相应字符串出现的次数
	public int countContent(String src,String dst){
	
		int count=0;//计数器
		int index=0;//下标
		index=src.indexOf(dst);
		while(index!=-1){
			count++;
			index+=dst.length();
			index=src.indexOf(dst,index);
		}
		
		return count;

	}
	public static void main(String[] args){
		
		Employee emp=new Employee();
		emp.name="张三";
		emp.age=30;
		System.out.println(emp.toString());
		
		String src="朋友啊朋友,你永远是我的朋友";
		String dst="朋友";
		System.out.println(emp.countContent(src,dst));
		
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值