java基础

7.常用类库

7.1String,StringBuffer,StringBuilder如何创建对象?有哪些常用方法?相互转换【String与基本数据类型 / String与字节数组/字符数组】?

答:String----Java中的字符串【字符串是程序中使用最广泛,处理最多的数据,因此java就提供了专门针对字符串处理的java类】

1.java.lang.String由于String类是属于java.lang包,因此在使用的时候不需要导包。

2.String类的定义

public final class String

extends Object

implements Serializable, Comparable<String>, CharSequence

3.使用了final 修饰符,说明String类没有子类,不可被继承。

3.实现了implements Serializable, Comparable<String>, CharSequence

4.String类的使用

(1).可以像基本数据类型使用方式一样创建对象。

int  a=100;

String  s=”hello”;   ”hello”--字符串常量

(2)可以通过String类提供的构造方法创建对象

String常用构造方法:

String() 创建一个空字符串对象。

String(String original) 通过指定的字符串常量,创建一个字符串对象。

String(byte[] bytes, int offset, int length)通过字节数组创建一个字符串对象。【字节数组转换成字符串】。

String(char[] value, int offset, intcount) 通过字符数组创建一个字符串对象。【字符数组转换成字符串】。

例如:

package com.click369.test1;
public class StringTest1 {
	public static void main(String[] args) {
		String  s1="hello";
		String  s2=new String();
		String  s3=new String("hello");
		byte  bytes[]={97,98,99,100};
		String  s4=new String(bytes,0,4);
		System.out.println("s4=="+s4);
		char  value[]={'h','e','l','l','o'};
		String  s5=new String(value,0,value.length);
		System.out.println("s5=="+s5);
	}
}

String类中常用方法的使用:

1.public char charAt(int index)得到原始字符串的指定位置[从0开始]的字符

2.public byte[] getBytes(String charsetName)

public byte[] getBytes()

3.public boolean equals(Object anObject)

4.public boolean equalsIgnoreCase(String anotherString)不考虑大小写

5.public boolean startsWith(String prefix)

6.public boolean endsWith(String suffix)

7.public int indexOf(String str)

8.public int lastIndexOf(String str)

9.public String substring(int beginIndex)

public String substring(int beginIndex,int endIndex)

10.public String concat(String str)

11.public String replace(String oldChar,String newChar)

12.public boolean matches(String regex)  匹配正则表达式

13.public boolean contains(String s)

14.public String[] split(String regex)

15.public String toLowerCase()转换为小写

16.public String toUpperCase()

17.public String trim()

18.public char[] toCharArray()

例如:

package com.click369.test1;

public class StringTest2 {

	public static void main(String[] args) {
		String  s1=new String("hello,world");
		//public char charAt(int index)得到原始字符串的指定位置[从0开始]的字符
		char ch=s1.charAt(5);
		System.out.println("ch=="+ch); //,
		//public byte[] getBytes(String charsetName)将原始字符按照指定字符编码转换成字节数组。
		//charsetName--字符编码【utf-8,GBK,GB2312...】
		//public byte[] getBytes()将原始字符换成字节数组。
		byte bytes[]=s1.getBytes();
		for(byte  b:bytes){
			System.out.println("b=="+b);
		}
		//?????????
		//public boolean equals(Object anObject)比较两个字符串是否相等。
		boolean b=s1.equals("hello,world");
		System.out.println("b=="+b);
		//public boolean equalsIgnoreCase(String anotherString)比较两个字符串是否相等,不考虑大小写
		boolean b1=s1.equalsIgnoreCase("HELLO,world");
		System.out.println("b1=="+b1);
		//public boolean startsWith(String prefix)前缀匹配【从一组用户名中得到所有姓李的用户名】
		String names[]={"李三","张三","李四","张四"};
		for(String name:names){
			if(name.startsWith("李")){
				System.out.println("name=="+name);
			}
		}
		//public boolean endsWith(String suffix)后缀匹配【从一组用户名中得到所有用“四”结尾的用户】
		for(String name:names){
			if(name.endsWith("四")){
				System.out.println("name=="+name);
			}
		}
		//public int indexOf(String str)得到指定字符串在原始字符串中第一次出现的位置。[没有就-1]
		int in=s1.indexOf("a");
		System.out.println("in=="+in);
		//public int lastIndexOf(String str)得到指定字符串在原始字符串中最后一次出现的位置。[没有就-1]
		int ind=s1.lastIndexOf("o");
		System.out.println("ind=="+ind);
		//public String substring(int beginIndex)截取字符串
		//public String substring(int beginIndex,int endIndex)【包前不包后】
		String sub1=s1.substring(2, 9);
		System.out.println("sub1=="+sub1);
		//http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg
		String imgurl="http://e.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3cef70d70409845d688d53f20f7.jpg";
		String imgname=imgurl.substring(imgurl.lastIndexOf("/")+1);
		System.out.println("imgname=="+imgname);
		//public String concat(String str) 类似与“+”,字符串链接符
		String newstr=s1.concat(",网星软件");
		System.out.println("newstr=="+newstr);
		//public String replace(String oldChar,String newChar)替换字符串
		String info="name=zhangsan,age=23";
		String newinfo=info.replace("zhangsan","lisi");
		System.out.println("newinfo=="+newinfo);
		//public boolean matches(String regex)  匹配正则表达式
		//public boolean contains(String s)判断指定的字符串是否在原始字符串中存在
		boolean  b2=s1.contains("Hello");
		System.out.println("b2=="+b2);
		//public String[] split(String regex)把原始字符串按照指定的分隔符拆分成String数组
		String info1="name=zhangsan,age=23";
		String  infoArray[]=info1.split("=");
		for(String  stri:infoArray){
			System.out.println("stri:"+stri);
		}
		//public String toLowerCase()转换为小写
		//public String toUpperCase()转换为大写
		//public String trim()//去除两端空格
		String s2="   zhang  san   ";
		System.out.println("s2:"+s2.length());
		String zhangsanstring=s2.trim();
		System.out.println("zhangsanstring:"+zhangsanstring.length());
		//public char[] toCharArray()将字符串转换成字符数组
		char  charray[]=s1.toCharArray();
		for(char c:charray){
			System.out.println("c=="+c);
		}
		
	}

}

 

StringBuilder----一final修饰的可变的字符序列

我们在需要很多的字符串相连接的时候,最好使用StringBuilder类,不要使用String类,因为使用String类会造成存储空间的浪费。

定义:

public final class StringBuilder

extends Object

implements Serializable, CharSequence

构造方法摘要

StringBuilder() 构造一个不带任何字符的字符串生成器,其初始容量为 16 个字符。

 

StringBuilder(int capacity) 构造一个不带任何字符的字符串生成器,其初始容量由 capacity 参数指定。

 

StringBuilder(String str) 构造一个字符串生成器,并初始化为指定的字符串内容。

 

例如:

                  StringBuilder  sbui1=new StringBuilder();

                  StringBuilder  sbui2=new StringBuilder(30);

                  StringBuilder  sbui3=new StringBuilder("hello");

                  

                  String s1="hello";  //  字符串常量池中创建一个"hello"

                  String s2="world";  //  字符串常量池中创建一个"world"

                  String s3="hello"+"world"; //字符串常量池中创建一个"helloworld";

                 

                  StringBuilder  sbui=new StringBuilder();//创建一个初始容量为16个字符的存储空间

                  sbui.append("hello"); //在16个字符的存储空间---》hello

                  sbui.append("world"); //在16个字符的存储空间---》helloworld

常用方法

1.StringBuilder  append(Object  o)向StringBuilder中追加任何类型的数据。

2.int capacity()返回当前容量。

3.char charAt(int index) 得到指定位置的字符数据

4.deleteCharAt(int index)移除此序列指定位置上的 char。

5.int indexOf(String str)得到指定的字符串在StringBuilder中第一次出现的位置。

6.lastIndexOf(String str)得到指定的字符串在StringBuilder中最后一次出现的位置。

7.insert(int offset,Object  o)向StringBuilder中的指定位置插入指定数据。

8.replace(int start, int end, String str)替换

9.reverse()将此字符序列用其反转形式取代。

10.String substring(int start)/substring(int start, int end)截取字符串,注意用String变量收取结果。

11toString()将StringBuilder转换成String

例如:

StringBuilder  sbui=new StringBuilder();//创建一个初始容量为16个字符的存储空间

                  sbui.append("hello"); //在16个字符的存储空间---》hello

                  sbui.append("world"); //在16个字符的存储空间---》helloworld

                  sbui.append(1234);

                  sbui.append(true);

                  sbui.append(12.34);

                  System.out.println(sbui);

                  //int capacity()返回当前容量。

                  System.out.println(sbui.capacity());

                  //char charAt(int index) 得到指定位置的字符数据

                  System.out.println(sbui.charAt(1));//e

                  //4.deleteCharAt(int index)移除此序列指定位置上的 char。

                  //["zhangsan","lisi","wangwu"]

                  String  names[]={"zhangsan","lisi","wangwu"};

                  StringBuilder  sbui11=new StringBuilder();

                  sbui11.append("[");

                  for(String name:names){

                          sbui11.append("\""+name+"\",");

                  }

                  sbui11.deleteCharAt(sbui11.length()-1);

                  sbui11.append("]");

                  System.out.println(sbui11);

                  //5.int indexOf(String str)得到指定的字符串在StringBuilder中第一次出现的位置。

                  //6.lastIndexOf(String str)得到指定的字符串在StringBuilder中最后一次出现的位置。

                  //7.insert(int offset,Object  o)向StringBuilder中的指定位置插入指定数据。

                  System.out.println(sbui);

                  sbui.insert(5, "##");

                  System.out.println(sbui);

                  //8.replace(int start, int end, String str)替换

                  sbui.replace(5, 7, "@@");

                  System.out.println(sbui);

                  //reverse()将此字符序列用其反转形式取代。

                  sbui.reverse();

                  System.out.println(sbui);

                  //10.String substring(int start)/substring(int start, int end)截取字符串,注意用String变量收取结果。

 

 

StringBuffer----线程安全的可变字符序列

定义:

public final class StringBuffer

extends Object

implements Serializable, CharSequence

构造方法摘要

StringBuffer()构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。

 

StringBuffer(int capacity)构造一个不带字符,但具有指定初始容量的字符串缓冲区。

 

StringBuffer(String str)构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。

 

 

1.StringBuffer append(Object  o)向StringBuffer中追加任何类型的数据。

2.int capacity()返回当前容量。

3.char charAt(int index) 得到指定位置的字符数据

4.deleteCharAt(int index)移除此序列指定位置上的 char。

5.int indexOf(String str)得到指定的字符串在StringBuffer中第一次出现的位置。

6.lastIndexOf(String str)得到指定的字符串在StringBuffer中最后一次出现的位置。

7.insert(int offset,Object  o)向StringBuffer中的指定位置插入指定数据。

8.replace(int start, int end, String str)替换

9.reverse()将此字符序列用其反转形式取代。

10.String substring(int start)/substring(int start, int end)截取字符串,注意用String变量收取结果。

11toString()将StringBuffer转换成String

 

字节数组与String的转换

         字节数组---->String [String的构造方法【String(byte[] bytes, int offset, int length)]

         String--->字节数组[String的public byte[]     ()]

字符数组与String的转换

        字符数组--->String[String的构造方法String(char[] value, int offset, int count)]

       String---->字符数组[String的public char[] toCharArray()]

 

基本数据类型与String的转换。

valueOf的静态方法

static String

valueOf(boolean b)返回 boolean 参数的字符串表示形式。

static String

valueOf(char c) 返回 char 参数的字符串表示形式。

static String

valueOf(double d) 返回 double 参数的字符串表示形式。

static String

valueOf(float f) 返回 float 参数的字符串表示形式。

static String

valueOf(int i) 返回 int 参数的字符串表示形式。

static String

valueOf(long l) 返回 long 参数的字符串表示形式。

基本数据类型[基本类型的封装类]

封装类---基本类型的封装类[只有基本类型具有封装类]

基本数据类型对应的复合数据类型【java类】

基本数据类型

封装类类型java类

byte[字节型]

Byte[java类]

short[短整型]

Short[java类]

int[整型]

Integer[java类]

long[长整型]

Long[java类]

float[单精度浮点型]

Float[java类]

double[双精度浮点型]

Double[java类]

char[字符型]

Character[java类]

boolean【布尔型】

Boolean[java类]

基本数据类型与对应的封装类的转换

基本数据类型----->对应的封装类[装箱操作]将基本类型的数据值/变量赋值给对应的封装类

1.将基本类型的数据值/变量赋值给对应的封装类

2.通过封装类的构造方法

例如:

//int num=100; //num是基本类型变量,没有可供调用的变量和方法

//Integer number=num; //装箱操作  //number对应的封装类对象,提供一系列可供调用的变量和方法。

//System.out.println("number=="+number);

//Integer number=100;

Integer  number1=new Integer(100);

int num=100;

Integer  number2=new Integer(num);

Integer  number3=new Integer("100"); //String---》int型封装类对象

 

对应的封装类----->基本数据类型[拆箱操作]将封装类对象转换基本数据类型

Integer  number21=new Integer(200);

int num1=number21; //拆箱操作

 

String----->基本数据类型[通过基本类型的封装类提供的parseXXX(String value)]

 

StringBuilder与String的转换

1.StringBuilder--->String

1.1通过StringBuilder的toString方法

1.2通过String的构造方法String(StringBuilder builder)

2.String-----》StringBuilder 

2.1通过StringBuilder的构造方法StringBuilder(String str)

2.2通过StringBuilder的append方法

7.2String,StringBuffer,StringBuilder区别?

答:

1.三者在执行速度方面的比较:StringBuilder >  StringBuffer  >  String

2.String <(StringBuffer,StringBuilder)的原因

    String:字符串常量

    StringBuffer:字符串变量

    StringBuilder:字符串变量

3.StringBuilder与 StringBuffer

    StringBuilder:线程非安全的

    StringBuffer:线程安全的

对于三者使用的总结: 1.如果要操作少量的数据用 = String

           2.单线程操作字符串缓冲区 下操作大量数据 = StringBuilder

           3.多线程操作字符串缓冲区 下操作大量数据 = StringBuffer

 

7.3Date/SimpleDataFormat如何创建对象?有哪些常用方法?

答:时间日期处理类---java.util.Date  类 Date 表示特定的瞬间,精确到毫秒。

创建对象:

Date  d1=new Date();

实例方法

after(Date when)测试此日期是否在指定日期之后。

before(Date when)测试此日期是否在指定日期之前。

toString() 将Date转换String.

Date(long date)构造方法得到当前系统时间

例如:

long haomiaoshu=System.currentTimeMillis();

Date  d3=new Date(haomiaoshu);

 //Thu Sep 05 10:55:28 GMT+08:00 2019

 System.out.println(d3);

时间日期格式转换----java.text.SimpleDateFormat---时间日期的格式化类

构造方法

SimpleDateFormat(String pattern) 通过指定的格式创建SimpleDateFormat对象

String pattern---时间日期格式。

实例方法

String format(Date date) 将一个 Date 格式化为日期/时间字符串

Date parse(String source) 从给定字符串的开始解析文本,以生成一个Date。

例如:

                  Date  d=new Date();

                  //设置时间日期格式

                  String  geshi="yyyy-MM-dd HH:mm:ss E";

                  //创建时间日期格式化对象

                  SimpleDateFormat  sdf=new SimpleDateFormat(geshi);

                  //通过format()方法格式时间日期

                  String newdate=sdf.format(d);

                  //2019-09-05 11:28:07 星期四

                  System.out.println(newdate);

                  try{

                  //String----时间日期格式----Date

                  String datetime="2019-09-05 11:28:07 星期四";

                  String  geshi1="yyyy-MM-dd HH:mm:ss E";

                  //创建时间日期格式化对象

                  SimpleDateFormat  sdf1=new SimpleDateFormat(geshi1);

                  Date dd=sdf1.parse(datetime);

                  //Thu Sep 05 11:28:07 GMT+08:00 2019

                  System.out.println(dd);

                  }catch(Exception e){

                          e.printStackTrace();

                  }

 

7.4Math类有哪些常用方法?

答:

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

成员变量

static double E 自然常数

static double PI 圆周率

静态方法

random() 得到0.0-1.0之间的随机数

round(float a)返回最接近参数的 int。

例如:

                  System.out.println("E=="+Math.E);

                  System.out.println("PI=="+Math.PI);

                  //静态方法

                  //random() 得到0.0-1.0之间的随机数

                  //System.out.println("random=="+Math.random());

                  //得到1--100之间的随机数

                  int d1=(int)(Math.random()*100);

                  System.out.println("d1=="+d1);

                  //round(float a)返回最接近参数的 int。

                  System.out.println("round=="+Math.round(11.5)); //12

                  System.out.println("round=="+Math.round(-11.5)); //-11   

 

7.5正则表达式?

正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个规则字符串,这个规则字符串用来表达对字符串的一种过滤逻辑。通常都是用来验证输入的字符串数据是否复合正则表达式定义的规范,常被用来做验证操作。

常用的正则表达式:

1. Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

2. 域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?

3. InternetURL:[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$

4. 手机号码(可根据目前国内收集号扩展前两位开头号码):^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$

5. 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$

6. 国内电话号码(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7}

7.15位身份证号:^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$

8.18位身份证号:^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$

9. 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$

10. 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$

11. 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$

12. 日期格式:^\d{4}-\d{1,2}-\d{1,2}

中文字符的正则表达式:[\u4e00-\u9fa5]

腾讯QQ号:[1-9][0-9]{4,}    (腾讯QQ号从10000开始)

中国邮政编码:[1-9]\d{5}(?!\d)    (中国邮政编码为6位数字)

IP地址:((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)

例如:

package com.click369.test1;
import java.util.Scanner;
public class ZhengZeTest1 {
	public static void main(String[] args) {
		/*
		String regex="^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";
		Scanner  input=new Scanner(System.in);
		System.out.println("请输入手机号码");
		String phoneNum=input.nextLine();
		boolean b=phoneNum.matches(regex);
		if(b){
			System.out.println("合法手机号码");
		}else{
			System.out.println("非法手机号码");
		}
		*/
		
		String regex="[\u4e00-\u9fa5]{2,4}";
		Scanner  input=new Scanner(System.in);
		System.out.println("请输中文:");
		String zhongwen=input.nextLine();
		boolean b=zhongwen.matches(regex);
		if(b){
			System.out.println("中文");
		}else{
			System.out.println("非中文");
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值