Java中的String常用类中的常用方法, Date日期类,转换格式,枚举类

Java中的String类

在java中,String类是不可不可变长的字符序列,java程序中所有的字符串字面值(如"abc")都作为此类的实例实现

简单介绍一下这些常用类的特性:

String:不可变长字符序列

StringBuilder:可变长,线程不安全,执行效率高

StringBuffer:可变长,线程安全,效率低

如何创建对象?—>构造器

通过java为我们提供的API文档来使用这些方法

String
public class StringDemo01{
    public static void main(String[]args)throws UnsupportedEncodingException{
		String s1="abc"; //1个 字符串常量池中的"abc"
		String s2=new String("haha"); //2个  堆中一个,字符串常量池中一个
		String s3=new String("abc"); //1个 堆中的new对象
        
        //String 类中提供的方法来创建字符串
        //String(char[] vaule)根据字符数组创建字符串
        char[] ch=new char[]{'s','h','s','x','t'};
        String s=new String(ch);
        System.out.println(s);//输出结果 shsxt
        
        //String(char[] vaule,int offset,int count)根据字符数组中的一部分创建一个字符串
        String s4=new String(ch,2,3);
        System.out.println(s4);//输出结果 sxt
        
        byte[]arr="中国".getBytes();
        //String(Byte[]byte) 通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
        String str5 =new String(arr);
        System.out.println(str5);//输出结果 中国
        
        //String(byte[] bytes, String charsetName)通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
        String str6=new String(arr,"utf-8");
        System.out.println(str6);//输出结果 中国
        
        //String(byte[] bytes, int offset, int length) 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
        //根据索引 offset 起始索引,length 长度
        String str7=new String(0,3);
        System.out.println(str7);//输出结果 中
        
        //StringBuffer和StringBuilder 转为字符串
		/*
		 *  String(StringBuffer buffer) 
			          分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。 
			String(StringBuilder builder)  
		 */
    }
}
字符串String常用方法
public class StringDemo02 {
	public static void main(String[] args) {
		String str="shsxtverygood";
        String str2="Shsxtverygood";
        //*** char charAt(int index)  根据索引找字符
		System.out.println("charAt:"+str.charAt(3));//输出结果 charAt():x
        //字符串 str中,索引为3的字符为x,所以返回x;
        
        // int codePointAt(int index) 返回指定索引处的字符(Unicode 代码点)。
		System.out.println("codePointAt():"+str.codePointAt(3));
        //输出结果为 codePointAt():120 在字符编码表中,字符'x'所指代的代码点就是120,所以返回120
        
        //int compareTo(String anotherString)  按字典顺序比较两个字符串。
		System.out.println("compareTo():"+str.compareTo(str2));
        //输出结果为 compareTo():32   大写和小之间相差32
        
        //*** String concat(String str)  将指定字符串连接到此字符串的结尾。
		System.out.println("concat():"+str.concat(str2));
        //输出结果为 concat():shsxtverygoodShsxtverygood
        //把名字为Str2的字符串连接到名字为str的字符串的结尾.
        
        /* 
          boolean contains(CharSequence s)  当且仅当此字符串包含指定的 char 值序列时,返回 				  true。 判断当前字符串是否包含某个字符
        */
        //判断名字为str的字符串里,是否包含"sxts",包含返回true,不包含返回false.
		System.out.println("contains():"+str.contains("sxts"));        
        // 输出结果为:contains():false
        
        //static String copyValueOf(char[] data)  字符数组转为字符串
		System.out.println("copyValueOf():"+String.copyValueOf(new char[]{'a','b','c'}));;
        // 输出结果为: copyValueOf():abc
        
        //boolean endsWith(String suffix) 测试此字符串是否以指定的后缀结束。
        //判断str字符串是否已"good"后缀结束,是返回true,不是返回false;
		System.out.println("endsWith():"+str.endsWith("good"));
        //输出结果 endsWith():true
        
        //startsWith(String prefix)  测试此字符串是否以指定的前缀开始。
        //判断此字符串是否以指定的前缀开始,如果是返回true,不是返回false.
        
        //***byte[] getBytes()   字符串的内容以字节数组形式返回
        
        //*** int indexOf(String str)   返回参数字符串在字符串中第一次出现的索引
        System.out.println("indexOf():"+str.indexOf("s"));
        //输出结果 indexOf():0   s 第一次出现的位置是字符数索引为0 的位置
        
        // int lastIndexOf(String str)   返回参数字符串在字符串中最后一次出现的索引
        // s 最后一次出现在字符数组名为str 的索引位置 为 2, 返回 2.
        System.out.println("lastIndexOf():"+str.lastIndexOf("s"));
        //输出结果 lastIndexOf():2
        
        //*** int length()   字符串中字符的个数
        //返回 名字为str的字符串中字符的个数 str字符的个位数为13
		System.out.println("length():"+str.length());
        //输出结果  length():13
        
        /*
        String replace(char oldChar, char newChar)  返回一个新的字符串,它是通过用 newChar 替换		  此字符串中出现的所有 oldChar 得到的。
        把字符串str中的所有 s 替换成 S 并且返回一个新的字符串
        */
		System.out.println("replace():"+str.replace("s","S"));
        //输出结果  replace():ShSxtverygood;
        
        //*** String[] split(String regex)  根据分隔符进行分隔字符,返回数组
		System.out.println(Arrays.toString("name=zhangsan&pwd=123".split("&")));
        //输出结果 : [name=zhangsan, pwd=123]
        
        //*** String substring(int beginIndex) 截取字符串,从起始位置开始,返回到最后
        //从名字为str的字符数组中,从索引为5 的位置截取字符返回,不包含5
		System.out.println("substring():"+str.substring(5));
        //输出结果  substring():verygood
        
        //*** String substring(int beginIndex, int endIndex)  注意:结束位置不包含
        //截取名字为str的字符串,从起始位置为5,结束位置为7的位置截取, 结束位置不包含
		System.out.println("substring():"+str.substring(5,7));
        //输出结果 substring():ve
        
        //*** char[] toCharArray()  字符串转为字符数组
        //将字符串str转为字符数组 的形式
		System.out.println(Arrays.toString(str.toCharArray()));
        //输出结果  [s, h, s, x, t, v, e, r, y, g, o, o, d]
        
        // String toLowerCase()  使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
		//String toUpperCase()   使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
        //将字符串名为str中的所有字符都转换为大写。
		System.out.println("toUpperCase():"+str.toUpperCase());
        //输出结果  toUpperCase():SHSXTVERYGOOD
        
        // String trim()  去除前后空格
		System.out.println("trim():"+(("  "+str).trim()));
        //输出结果 trim():shsxtverygood
       
        //static String valueOf(boolean b) 系列重载方法  参数转为字符串  
        //返回 char 参数的字符串表示形式。
		System.out.println("valueOf():"+String.valueOf(false));
        //输出结果  valueOf():false
	}
}

常用方法总结:

	char charAt(int index)  根据索引找字符 
    
    String concat(String str) 将指定字符串连接到此字符串的结尾。
        
    boolean contains(CharSequence s) 判断当前字符串是否包含某个字符
        
    byte[] getBytes()   字符串的内容以字节数组形式返回
        
    int indexOf(String str)   返回参数字符串在字符串中第一次出现的索引
	
    int lastIndexOf(String str)   返回参数字符串在字符串中最后一次出现的索引   
        
    int length()   获取字符串中字符的个数  
        
    String replace(char oldChar, char newChar) 把字符串中所有旧的字符替换成新的字符 
        
    String[] split(String regex)  根据分隔符进行分隔字符,返回数组
        
    String substring(int beginIndex) 截取字符串,从起始位置开始,返回到最后
        
    String substring(int beginIndex, int endIndex) 起始位置,结束位置 注意:结束位置不包含   
        
    char[] toCharArray()  字符串转为字符数组
        
    String toLowerCase()  使用默认语言环境的规则将此 String 中的所有字符都转换为小写

    String toUpperCase()   使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
        
        
StringBuilder 与 StringBuffer
/*
StringBuilder与StringBuffer都是一个可变的字符序列

如果只是想表示字符串,在没有大量对字符串中的内容进行改动,增删的情况,可以选择使用String,功能多,方便

如果对字符串中的内容,大量做改动,单线程环境下不需要考虑线程安全问题,推荐使用StringBuilder

如果多线程环境下包装安全,对子串进行可变操作,推荐使用StringBuffer

运行速度比较:StringBuilder > StringBuffer > String

StringBuilder 线程不安全,StringBuffer线程安全

底层存储数据都是通过字符数组
*/  

public class StringDemo03 {
	public static void main(String[] args) {
		//构造器
		//StringBuilder() 初始容量16个大小
		StringBuilder sb=new StringBuilder();
		System.out.println(sb);
		
		//StringBuilder(String str)   构造一个字符串生成器,并初始化为指定的字符串内容        
		StringBuilder sb2=new StringBuilder("abc");
		System.out.println(sb2);
        //输出结果 abc
		
		//StringBuilder(int capacity)  如果能够确定数据,字符串中字符的个数,推荐使用
		StringBuilder sb3=new StringBuilder(10);
		System.out.println(sb3);
		
		//新增方法   修改原StringBuilder对象
		//StringBuilder append(CharSequence s),向此 Appendable 添加指定的字符序列。 
		StringBuilder s=sb2.append(false); //int newCapacity = (value.length << 1) + 2;
		System.out.println(s);
		System.out.println(sb2);
		
		sb2.append("12345678911");
		
		// int capacity()  
		System.out.println(sb2.capacity());
		System.out.println(sb2.length()); //字符串中字符的个数
        //追加加一个字符为"1"的字符
		sb2.append("1");
		System.out.println(sb2.capacity()); 
        //输出结果为  40
		System.out.println(sb2.length());
		//输出结果为 20
		System.out.println(sb2);
        //输出结果 abcfalse123456789111
		
		// StringBuilder delete(int start, int end)   删除指定索引范围的内容,结束索引不包含
        //删除起始索引为3,到结束索引为8的字符,不包含8.
		System.out.println(sb2.delete(3,8));
		//输出结果 abc123456789111
        
		//StringBuilder insert(int offset, double d) 插入数据
		System.out.println(sb2.insert(6, "哈哈"));
        //输出结果 abc123哈哈456789111
		
		//StringBuilder reverse()   反转字符串中的顺序
		System.out.println(sb2.reverse());
        //输出结果  111987654哈哈321cba
		
		new StringBuffer("hehe").reverse();
	}
	
}
/*
	总结:StringBuilder 新增的方法:
	
		StringBuilder(String str)   构造一个字符串生成器,并初始化为指定的字符串内容   
		
		新增方法   修改原StringBuilder对象
		StringBuilder append(CharSequence s),向此 Appendable 添加指定的字符序列
		
		StringBuilder delete(int start, int end)   删除指定索引范围的内容,结束索引不包含
		
		StringBuilder insert(int offset, double d) 插入数据, offset:起始索引
		
		StringBuilder reverse()   反转字符串中的顺序
*/	
基本数据类型的包装类
/*
	基本数据类型的包装类名称:
	byte-->Byte
	short-->Short
	int-->Integer
	long-->Long
	char-->Character
	float-->Float
	double-->Double
	boolean-->Boolean
	
	转换:
		自动拆装箱:
			自动装箱:从基本-->引用
			自动拆箱:从引用-->基本
*/
public class DataDemo01 {
	public static void main(String[] args) {
		int i=5;
		//自动装箱		Integer.valueOf(i) 返回一个Integer类型的数据
		Integer in=i;
		//自动拆箱 		in.intValue() 返回一个int类型的表示该对象的数据
		int x=in;
		
		test(1.1,2.2); //自动装箱  结果为:3.3000000000000003
		
		Integer i1= 127;
		Integer i2= 127;
		Integer i3= 128;
		Integer i4= 128;
		System.out.println(i1==i2);  //true
       //如果Integer,只要在缓冲区对象表示范围中-128~127中间,就相等,否则返回new Integer(),新对象地址
		System.out.println(i3==i4);  //false
		
		Integer i5= new Integer(127);
		Integer i6= new Integer(127);
		System.out.println(i1==i5);  //false
		System.out.println(i6==i5);  //false
		
		int i7=127;
		System.out.println(i7==i5);  //先发生自动拆箱   true
		System.out.println(i7==i1);  //true
		
		/*
		 * 总结:
		 * 	1.如果是两个new 的 Integer去比较|Integer和new Integer去比较,肯定不相等,new->堆中对象				地址 Integer->指向常量池中的地址
		 *  2.基本数据类型int和Integer比较(无论是否存在new),只要数据值相等就想等,因为会发生自动拆箱
		 *  3.如果Integer,只要在缓冲区对象表示范围中-128~127中间,就相等,否则返回new Integer()
		 */
	}
	
	static void test(Double d1,Double d2){
		System.out.println(d1+d2);  //自动拆箱
	}
}
Date日期类
/*
	构造器:
	Date() 分配Date 对象并且初始化此对象,以表示分配它的时间(精确到毫秒).显示的是本地时间
	Date(Long date)即1970年1月1日00:00:00 GMT)以来的指定毫秒数.
	
*/
public class DateDemo01 {
	public static void main(String[] args) {
		//构造器 
        //创建Date对象并且初始化值,显示的是本地时间
		Date date=new Date();
		System.out.println(date);
        //输出结果 Sun Dec 01 18:55:39 CST 2019
        //返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
		System.out.println(date.getTime());
		//输出结果  1575197739847
        
		Date date2=new Date(1575197725830L);
		System.out.println(date2);
        //输出结果 Sun Dec 01 18:55:25 CST 2019
		
		//	boolean after(Date when) 
		//	测试此日期是否在指定日期之后
		System.out.println(date.after(date2));
        //输出结果 true
	}
}
/*
	日期常用方法:
		 boolean after(Date when) 
			     测试此日期是否在指定日期之后。 
		 boolean before(Date when) 
			     测试此日期是否在指定日期之前。 
		 int compareTo(Date anotherDate) 
			     比较两个日期的顺序。 
		 boolean equals(Object obj) 
			     比较两个日期的相等
*/


SimpleDateFormat
/*
构造器:
	SimpleDateFormat() 默认的转换格式
	SimpleDateFormat("定义转换格式")默认的转换格式
	
	y 年
	M 月
	d 日
	H 24小时制
	h 12小时制
	m 分
	s 秒
	S 毫秒
*/

public class SimpleDateFormat02 {
	public static void main(String[] args) throws ParseException {
		//默认转换格式  19-11-30 下午4:07
		SimpleDateFormat simple= new SimpleDateFormat();  //19-11-30 下午4:07
		System.out.println(simple.format(new Date()));
        //输出结果 19-12-1 下午8:22
		
		SimpleDateFormat simple2= new SimpleDateFormat("yyyy/MM/dd E HH:mm:ss SSS"); 
		System.out.println(simple2.format(new Date()));
        //输出结果 2019/12/01 星期日 20:22:41 475
		
        //System.out.println(simple2.parse("2000/1/30 16:10:51 668"));
	}
}
枚举类enum
/*
	enum 枚举类:列举出所有情况
	定义枚举类,使用关键字enum
	枚举类中的字段,可以表示枚举类中的实例
	枚举类中的字段,相当于该类的一个实例 public static final
	所有的枚举类都隐式的继承自java.lang.enum
*/
public class EnumDemo01 {
	public static void main(String[] args) {
		System.out.println(WeekDay.Monday);
        //输出结果 Monday
        //类名.Monday 赋值给 mon,mon拿到地址几个调用WeekDay里的方法
		WeekDay mon=WeekDay.Monday; 
        //设置枚举类中Monday的名字
		mon.setName("星期一");
        //调用枚举类中的haha() 方法 
		mon.haha();
		
		//new WeekDay();
		
		mon=WeekDay.Tuesday;
		//switch(枚举)
		switch(mon){
			case Monday:
				mon.setName("星期一");
				break;
			case Tuesday:
				mon.setName("星期二");
				break;
			case Sunday:
				mon.setName("星期天");
				break;
		}
		mon.haha();
		//返回枚举常量的名字
		System.out.println(mon.name());
		// int ordinal() 返回在枚举常量中声明的位置,索引从0开始
		System.out.println(mon.ordinal());
		//输出结果  1
        //返回带指定名称的指定枚举类型的枚举常量。
		System.out.println(Arrays.toString(mon.values()));
		//输出结果  [Monday, Tuesday, Wednesday, Sunday]
	}
}
//枚举类
enum WeekDay{
	//字段
	Monday,  //WeekDay mondy=new WeekDay();
	Tuesday,
    Wednesday,
    Sunday;
	
	//成员变量
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	//成员方法 
	public void haha(){
		System.out.println("今天是"+name);
	}
/*
	方法总结:
			int ordinal() 返回在枚举常量中声明的位置,索引从0开始
			
			valueOf(Class<T> enumType, String name) 
          返回带指定名称的指定枚举类型的枚举常量。
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值