java学习第14天--character类-正则表达式-SimpleDateFormat-工具类

character类
character类概念的讲解
Character 类在对象中包装一个基本类型 char 的值。
此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然。
构造方法:
Character(char value)
    构造一个新分配的 Character 对象,用以表示指定的 char 值。

都是静态方法
boolean isUpperCase(char ch)
boolean isLowerCase(char ch)
boolean isDigit(char ch)
char toUpperCase(char ch)
char toLowerCase(char ch)

character类的练习
1.求出下列字符串中的大小写字符,数字字符和其他字符的个数
String s = "abcDEF123+-*/";

package com.czz_test;
 
/*
 * 求出下列字符串中的大小写字符 , 数字字符和其他字符的个数
 * */
 
public class CharacterDemo {
   public static void main(String[] args ) {
      // 自定义字符串变量
      String str = "abcDEF123+-*/" ;
      // 将字符串转为字符数组
      char [] chs = str .toCharArray();
     
      int lower = 0;
      int upper = 0;
      int digit = 0;
      int other = 0;
     
      // 方法一使用 charAt
      /*for ( int i = 0; i < chs.length; i++) {
         char charAt = str.charAt(i);
         if(Character.isUpperCase(charAt)) {
            upper++;
         }else if(Character.isLowerCase(charAt)) {
            lower++;
         }else if(Character.isDigit(charAt)) {
            digit++;
         }else{
            other++;
         }
      }*/
     
      // 方法二使用字符数组 :toCharArray
      for ( int i = 0; i < chs . length ; i ++) {
         if (Character. isUpperCase ( chs [ i ])) {
            upper ++;
         } else if (Character. isLowerCase ( chs [ i ])) {
            lower ++;
         } else if (Character. isDigit ( chs [ i ])) {
            digit ++;
         } else {
            other ++;
         }    
      }
     
      System. out .println( " 大写字符个数为 :" + upper );
      System. out .println( " 小写字符个数为 :" + lower );
      System. out .println( " 数字字符个数为 :" + digit );
      System. out .println( " 其他字符个数为 :" + other );
   }
}
 
2.
把一个字符串中用空格分隔的单词的首个字符转成大写.
Tom Is A Student

package com.czz_test;
 
/*
 * 把一个字符串中用空格分隔的单词的首个字符转成大写 .
   Tom Is A Student
 */
 
public class Demo1 {
 
   public static void main(String[] args ) {
      String str = "tom is a student" ;
     
      // 创建 sb 对象
      StringBuffer sb = new StringBuffer();
     
      // 以空格为间隔切割 str 字符串 , 并将切完之后的字符先暂时放到 words 字符数组中
      String[] words = str .split( " " );
     
      // 循环对 words 字符数组进行操作
      for ( int i = 0; i < words . length ; i ++) {
         // 先使用 substring 切字符 , 并将第一个字符经过 toUpperCase 变为大写 , 并将后面的字符加上 ,substring(1) 表示从第 2 个字符一直到最后
         String w words [ i ].substring(0, 1).toUpperCase() + words [ i ].substring(1);
         sb .append( w ).append( " " );
      }
      System. out .println( sb .toString());
   }
}
 

正则表达式:符合一定规则的字符串
字符
    x 字符
    \\ 反斜线
    \r 回车
    \n 换行
字符类
    [abc] 任意一个
    [a-z] 小写字符中的任意一个
预定义字符类
    . 任意字符,如果匹配.本身,用\.
    \d 数字字符,等价于[0-9]
    \w 单词字符,等价于[a-zA-Z_0-9]
边界
    \b 单词边界,hello world?nihao+hehe
数量词
    X{n} 正好n次
    X{n,} 至少n次
    X{n,m} n到m次

正则表达式练习
1. 验证QQ号,不能以0开头,5-10位,纯数字组成
package com.czz_test;
 
import java.util.Scanner ;
 
/*
 * 验证 QQ , 不能以 0 开头 ,5-10 , 纯数字组成
 * */
 
public class Demo3 {
   public static void main(String[] args ) {
      Scanner sc = new Scanner (System. in );
     
      while ( true ) {
         System. out .println( " 请输入您的 QQ :" );
         String num = sc .next();
         boolean check = check ( num );
         System. out .println( check );
      }
   }
 
   // 核实信息
   public static boolean check(String num ) {
      String pattern = "[1-9][0-9]{3,9}" ;
      boolean matches = num .matches( pattern );
      return matches ;
   }
}
 
2.
根据输入的固定电话的区号,判断电话号码的归属地
01012345678 显示"北京"
02012345678 显示"广州"
其他显示其他
package com.czz_test;
 
import java.util.Scanner;
 
/*
 * 010 北京
 * 020 广州
 * ... 其它
 */
 
public class Demo4 {
 
public static void main(String[] args ) {
   Scanner scanner = new Scanner(System. in );
  
   while ( true ){
      System. out .println( "input a num:" );
      String num = scanner .next();
      String province = getProvince ( num );
      System. out .println( province );
   }
}
 
   public static String getProvince(String n ){
      String province = null ;
      // 定义模式 ( 正则表达式 )
      String bj = "010[0-9]{8}" ;
      String gz = "020[0-9]{8}" ;
      //...
 
      if ( n .matches( bj )){
         province = " 北京 " ;
      } else if ( n .matches( gz )){
         province = " 广州 " ;
      } else {
         province = "other" ;
      }
      return province ;
   }
}
也可以 采用下面的方式



3.找到一个字符串中四个字符,并且第一个字符是t,w,a,e的单词
package com.czz_regex;
 
/*
 * 找到一个字符串中四个字符 , 并且第一个字符是 t,w,a,e 的单词
 * */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexDemo4 {
   public static void main(String[] args ) {
      String ss = "THea class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class. "
            + "The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification."
            + "Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown."
            + "A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String."
            + "The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values)." ;
     
      int count = 0;
      String pattern = "\\b[twae][a-zA-Z]{3}\\b" ;
      Pattern p = Pattern. compile ( pattern );
      Matcher m = p .matcher( ss );
     
      while ( m .find()) {
         count ++;
         System. out .println( m .group());
      }
      System. out .println( " 个数总共为 :" + count );
   }
}
 
4.有一个字符串,单词之间的空格个数不确定.如何将每个单词输出?
例如:String s = "hello world     he       hehe nihao               hello";
package com.czz_test;
 
/*
 * 有一个字符串 , 单词之间的空格个数不确定 . 如何将每个单词输出 ?
 */
public class StringSplit {
 
   public static void main(String[] args ) {
      String s = "hello world     he       hehe nihao               hello" ;
     
      String[] words = s .split( " +" );
      for ( int i = 0; i < words . length ; i ++) {
         System. out .println( words [ i ]);
      }
   }
}
 
SimpleDateFormat
构造方法
SimpleDateFormat()
SimpleDateFormat(String pattern)
如果使用空参的构造方法,表示使用的是默认的格式,不利于理解
带参构造中参数的含义:
一个字符串,字符串中的字符有特殊含义,例:
y:年  M:月份  d:日期  H:小时   m:分钟   s:秒
“yyyy年MM月 HH:mm:ss”  :四位年份值,两位月份值,其余都是两位

格式化:
String pattern = “yyyy MM dd HH:mm:ss”;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date d = new Date();
String res = sdf.format(d);
解析:此时需要解析的文本必须用格式化时的模式才能解析
String strDate = “2010年10月10日 10:10:10”;
String pattern = “yyyy年MM月dd日 HH:mm:ss”;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date d = sdf.parse(strDate);

练习
package com.test;
 
import java.text.SimpleDateFormat ;
import java.util.Date;
 
public class SimpleDateFormatDemo {
   public static void main(String[] args ) {
      // 定义 pattern 字符串 , 也就是格式化后的字符串
      String pattern = "yyyy MM dd HH:mm:ss" ;
     
      // 使用 SimpleDateFormat 类将 pattern 字符串进行格式化
      SimpleDateFormat sdf = new SimpleDateFormat ( pattern );
 
      // 创建当前日期对象 , 获取当前系统时间
      Date d = new Date();
 
      // 表示将当前系统时间格式化为以 pattern 的形式
      String format = sdf .format( d );
     
      // 将格式化后的形式打印
      System. out .println( format );
   }
}
 
工具类的使用
请看代码:

DateTool工具代码:
package com.test;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * 日期的工具类
 * */

public class DateTool {
   // 构造方法私有化
   private DateTool() {
     
   }
  
   // 格式化一个日期对象 , 形参列表 ( 需要转的对象 , 转换成什么格式 )
   public static String dateToString(Date d ,String pattern ) {
      //
      SimpleDateFormat sdf = new SimpleDateFormat( pattern );     
      // 将传进来的对象格式化
      String format = sdf .format( d );
      // 将格式化后的对象打印
      return format ;
   }
   
   // 把字符串解析成日期对象
   public static Date stringToDate(String date ,String pattern ) throws ParseException {
      SimpleDateFormat sdf = new SimpleDateFormat( pattern );
      Date d = sdf .parse( date );
      return d ;
   }  
}
 
工具类的Demo使用:
package com.test;
 
import java.text.ParseException;
import java.util.Date;
 
public class DateToolDemo {
 
   public static void main(String[] args ) {
 
      Date d = new Date();
      String pattern = "yyyy-MM-dd" ;
      // 调用工具类格式化日期对象
      String res = DateTool. dateToString ( d , pattern );
      System. out .println( res );
     
      // 调用工具类解析一个字符串成日期对象
      try {
         Date date = DateTool. stringToDate ( res , pattern );
         System. out .println( date );
      } catch (ParseException e ) {
         System. out .println( " 字符串解析异常 " );
         e .printStackTrace();
      }
   }
}

练习之: 
算一下你来到这个世界多少天?
思路:
1. 我们知道的是生日,是字符串的形式
2. 用工具类将这个字符串转换成一个日期对象 :Date d (1980,01,01)
3. 得到生日对象的毫秒值
4. 得到现在系统的毫秒值
5. 得到二者的毫秒差
6. 使用毫秒差换算得到天数

package com.test;
 
import java.text.ParseException;
import java.util.Date;
 
/*
 * 算一下你来到这个世界多少天?
   思路:
   1. 我们知道的是生日,是字符串的形式
   2. 用工具类将这个字符串转换成一个日期对象 :Date d (1980,01,01)
   3. 得到生日对象的毫秒值
   4. 得到现在系统的毫秒值
   5. 得到二者的毫秒差
   6. 使用毫秒差换算得到天数
 * */
  DateTool工具代码:
package com.test;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * 日期的工具类
 * */

public class DateTool {
   // 构造方法私有化
   private DateTool() {
     
   }
  
   // 格式化一个日期对象 , 形参列表 ( 需要转的对象 , 转换成什么格式 )
   public static String dateToString(Date d ,String pattern ) {
      //
      SimpleDateFormat sdf = new SimpleDateFormat( pattern );     
      // 将传进来的对象格式化
      String format = sdf .format( d );
      // 将格式化后的对象打印
      return format ;
   }
   
   // 把字符串解析成日期对象
   public static Date stringToDate(String date ,String pattern ) throws ParseException {
      SimpleDateFormat sdf = new SimpleDateFormat( pattern );
      Date d = sdf .parse( date );
      return d ;
   }  
}
工具类的使用
public class DateToolDem02 { 
   public static void main(String[] args) throws ParseException {
      String birthday = "1992-12-21" ;
      Date date = DateTool.stringToDate(birthday, "yyyy-MM-dd" );
 
      long time = date.getTime();
      Date date2 = new Date();
      long time2 = date2.getTime();
 
      long time3 = time2 - time;
      System.out.println(time3 / 1000 / 3600 / 24);
   } 
}
 







猜你喜欢

转载自blog.csdn.net/czz1141979570/article/details/79995029