字符串相关类
String类:构造字符串对象
常量对象:字符串常量对象是用双引号括起的字符序列。 例如:“你好”、“12.97”、"boy"等。
字符串的字符使用Unicode字符编码,一个字符占两个字节
String类较常用构造方法:
String s1 = new String();
String s2 = new String(String original);
String s3 = new String(char[] a);
String s4 = new String(char[] a,int startIndex,int count)
String str = “abc”;与String str1 = new String(“abc”);的区别?
字符串的特性
String是一个final类,代表不可变的字符序列
字符串是不可变的。一个字符串对象一旦被配置,其内容是不可变的。
字符串与基本数据的相互转化
字符串转换为基本数据类型
Integer包装类的public static int parseInt(String s):可以将由“数字”字符组成的字符串转换为整型。
类似地,使用java.lang包中的Byte、Short、Long、Float、Double类调相应的类方法可以将由“数字”字符组成的字符串,转化为相应的基本数据类型。
基本数据类型转换为字符串
调用String类的public String valueOf(int n)可将int型转换为字符串
相应的valueOf(byte b)、valueOf(long l)、valueOf(float f)、valueOf(double d)、valueOf(boolean b)可由参数的相应类到字符串的转换
常用的String类方法
package com.atguigu.javase.string;
import org.junit.Test;
import javax.swing.*;
/**
* String : 是内容不可改变的Unicode字符序列(CharSequence).
* 可以简单地理解为是一个char[]
* 0 2 10 15 21 27 32 34
* String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
*
* ###public int length(). string.length() => 35 获取字符串长度(字符数)
* ###public char charAt(int index) 获取指定下标位置处的字符 string.charAt(12) => '欢', string.charAt(18) => '我';
* ##public char[] toCharArray() 获取内部的char[]
* char result[] = new char[value.length]; // 创建一个新数组, 容量和内部的value一样大.
*
* for (int i = 0; i < value.length; i++) {
* result[i] = value[i];
* }
*
* System.arraycopy(value, 0, result, 0, value.length);
* // 第一个参数是源数组对象, 第二个参数是源数组的开始下标, 第三个参数是目标数组对象, 第四个参数是目标数组的开始下标
* // 第五个参数是要复制的元素个数.
* public boolean equals(Object anObject)
* public boolean equalsIgnoreCase(String anotherString) 比较字符串内容, 忽略大小写
* public int compareTo(String anotherString)
*
* 0 2 10 15 21 27 32 34
* String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
*
* #####
* public int indexOf(String s), 获取参数中的子串在当前字符串中首次出现的下标. 如果不存在返回-1
* string.indexOf("喜欢") => 11
* string.indexOf("讨厌")
* public int indexOf(String s ,int startpoint)获取参数中的子串在当前字符串中首次出现的下标. 从startPoint位置开始搜索
* string.indexOf("喜欢", 12) => 16, string.indexOf("喜欢", 17) => 23
*
* public int lastIndexOf(String s)
* string.lastIndexOf("喜欢") => 23
* public int lastIndexOf(String s ,int startpoint)
* string.lastIndexOf("喜欢", 22) => 16, string.lastIndexOf("喜欢", 15) => 11
*
* public boolean startsWith(String prefix) 判断当前串是否以参数中的子串为开始
* public boolean endsWith(String suffix)判断当前串是否以参数中的子串为结束
*
* 0 2 10 15 21 27 32 34
* String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
*
* #####
* public String substring(int start,int end) 从当前字符串中取子串, 从start开始(包含),到end结束(不包含)
* string.substring(10, 14) => "我喜欢你";
* public String substring(int startpoint) 从当前字符串中取子串, 从start开始(包含),到最后
*
* public String replace(char oldChar,char newChar) 替换字符串中的所有oldChar为newChar
* string.replace(' ', '#') =>
*
* // 参数中的字符串符合 正则表达式.
* public String replaceAll(String old,String new) 替换字符串中的所有old子串为new子串.
*
* public String trim() 修剪字符串首尾的空白字符. 空白字符就是码值小于等于32的字符
*
* public String concat(String str) 字符串连接
* public String toUpperCase() 变成大写
* public String toLowerCase() 变成小写
* String s = "abc,yy,123,qq,我和你,zzz";
* String[] arr = s.split(",");
* public String[] split(String regex) 以参数 中的子串为切割器,把字符串切割成多个部分.
*/
public class StringTest {
@Test
public void test8() {
String s1 = "abc";
String s2 = "ABC";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.toLowerCase().equals(s2.toLowerCase()));
}
@Test
public void test7() {
String s = "abc,yy,123,qq,我和你,zzz";
String[] arr = s.split(",");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
@Test
public void test6() {
class A {};
String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
String s = string.toUpperCase();
System.out.println(s);
String s1 = string.toLowerCase();
System.out.println(s1);
}
@Test
public void test5() {
String string = " \r\n\t \b abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 \r\n\t\t\t \b ";
System.out.println(string);
String trim = string.trim();
System.out.println("trim = " + trim);
}
@Test
public void test4() {
String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
String replace = string.replace(' ', '#');
System.out.println(replace);
String replace1 = string.replace("喜欢", "爱慕");
System.out.println(replace1);
String s2 = string.replaceAll("喜欢", "特别讨厌,真的讨厌");
System.out.println(s2);
// 消除字符串中的所有空格
String s = string.replaceAll(" ", "");
System.out.println(s);
String s3 = string.replaceAll("", "@");
System.out.println(s3);
}
//将一个字符串进行反转。将字符串中指定部分进行反转。比如将“abcdefg”反转为”abfedcg”
@Test
public void exer3() {
String string = "abcdefg";
int begin = 2;
int end = 6;
// 切成3段, 只反转中间部分.
String s1 = string.substring(0, begin);
String s2 = string.substring(begin, end);
String s3 = string.substring(end);
char[] chars = s2.toCharArray();
for (int i = 0; i < chars.length / 2; i++) {
char tmp = chars[i]; //
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = tmp;
}
String result = s1 + new String(chars) + s3;
System.out.println("result = " + result);
}
@Test
public void test3() {
String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
String substring = string.substring(10, 14);
System.out.println("substring = " + substring);
String substring2 = string.substring(10, string.length());
System.out.println("substring2 = " + substring2);
}
@Test
public void test2() {
String string = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
boolean b = string.startsWith(" abc");
System.out.println(b);
boolean b2 = string.endsWith("zzz123");
System.out.println(b2);
}
/*获取一个字符串在另一个字符串中出现的次数。
比如:获取"ab"在 "abkkcadkabkebfkabkskab"
中出现的次数*/
@Test
public void exer2() {
String s1 = "ababa";
String s2 = "aba";
int count = 0;
int index = 0;
while (true) {
index = s1.indexOf(s2, index);
//if (从长串中检索短串的下标时, 返回-1) {
if (index == -1) {
//结束这个过程
break;
}
count++;
index++;
}
System.out.println(count);
}
@Test
public void test1() {
String string = new String();
String s1 = new String("abc");
String s2 = new String("abC");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s1.compareTo(s2));
String string2 = " abcAQQY 我喜欢你,你喜欢我吗?我不喜欢你 zzz123 ";
int indexOf = string2.indexOf("讨厌");
System.out.println(indexOf);
}
}
StringBuilder类介绍
package com.atguigu.javase.string;
import org.junit.Test;
/**
* StringBuilder : 是内容可以改变的Unicode字符序列.
* <p>
* 1. StringBuffer()初始容量为16的字符串缓冲区
* 2.StringBuffer(int size)构造指定容量的字符串缓冲区
* 3.StringBuffer(String str)将内容初始化为指定字符串内容
* <p>
* StringBuilder append(...) 追加任意数据到当前串末尾.
* StringBuilder insert(int index, ...) 在指定位置处插入任意内容
* StringBuilder delete(int beginIndex, int endIndex) 删除一个区间
* StringBuilder setCharAt(int index, char ch) 替换指定下标处的字符为ch
* <p>
* private int newCapacity(int minCapacity) {
* // overflow-conscious code
* int newCapacity = (value.length << 1) + 2;
* if (newCapacity - minCapacity < 0) {
* newCapacity = minCapacity;
* }
* return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
* ? hugeCapacity(minCapacity)
* : newCapacity;
* }
* <p>
* StringBuffer : 古老的类 速度慢 线程安全, 不使用
* StringBuilder : 新的类 速度快 线程不安全.
*/
public class StringBuilderTest {
@Test
public void test5() {
String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str); // "abc" + null
String str2 = "abc";
str2 += null;
System.out.println(str2);
System.out.println(sb);
//String s = new String(str);
//System.out.println(s);
StringBuffer stringBuffer = new StringBuffer(str);
System.out.println(stringBuffer);
}
@Test
public void test4() {
String text = "";
long startTime = 0L;
long endTime = 0L;
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
@Test
public void test3() {
StringBuilder stringBuilder = new StringBuilder(); // 内部容量为16
stringBuilder.append(123);
stringBuilder.append("abc");
stringBuilder.append(3.14);
stringBuilder.append(true);
stringBuilder.append('我');
stringBuilder.append('你');
stringBuilder.append('A');
}
// 声明3个字符串, 赋值一些内容, 把第一个直接变成StringBuffer对象, 把第2个串追加在末尾, 把第3个串插入到最前面.
// 打印输出.
@Test
public void exer1() {
String s1 = "abclkjafd";
String s2 = "234239487234";
String s3 = "我是一些汉字";
StringBuilder insert = new StringBuilder(s1).append(s2).insert(0, s3);
System.out.println(insert);
}
@Test
public void test2() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(123).append("abc").append(3.14).append(true).append('A').insert(3, "我和你").delete(6, 10).setCharAt(3, '好');
System.out.println(stringBuilder);
}
@Test
public void test1() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(123);
stringBuilder.append("abc");
stringBuilder.append(3.14);
stringBuilder.append(true);
stringBuilder.append('A'); //123abc3.14trueA
stringBuilder.insert(3, "我和你"); //123我和你abc3.14trueA
System.out.println(stringBuilder);
stringBuilder.delete(6, 10);
System.out.println(stringBuilder); //123我和你.14trueA
stringBuilder.setCharAt(3, '好');
System.out.println(stringBuilder);
//StringBuilder stringBuilder2 = new StringBuilder(1024);
//System.out.println(stringBuilder2.length());
}
}
日期类
1.java.lang.System类
System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
此方法适于计算时间差。
2. java.util.Date类
表示特定的瞬间,精确到毫秒
构造方法:
Date( )使用Date类的无参数构造方法创建的对象可以获取本地当前时间。
Date(long date)
常用方法
getTime():返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
toString():把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat),zzz是时间标准。
Date类的API不易于国际化,大部分被废弃了,java.text.Simp
leDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类。
它允许进行格式化(日期–>文本)、解析(文本–>日期)
格式化:
SimpleDateFormat() :默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern):该构造方法可以用参数pattern指定的格式创建一个对象,该对象调用:
public String format(Date date):方法格式化时间对象date
解析:
public Date parse(String source):从给定字符串的开始解析文本,以生成一个日期。
3. java.util.Calendar(日历)
Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能。
获取Calendar实例的方法
使用Calendar.getInstance()方法
调用它的子类GregorianCalendar的构造器。
一个Calendar的实例是系统时间的抽象表示,通过get(int field)方法来取得想要的时间信息。比如YEAR、MONTH、DAY_OF_WEEK、HOUR_OF_DAY 、MINUTE、SECOND
public void set(int field,int value)
public void add(int field,int amount)
public final Date getTime()
public final void setTime(Date date)
4. 新时间日期API
Java 的日期与时间 API 问题由来已久,Java 8 之前的版本中关于时间、日期及其他时间日期格式化类由于线程安全、重量级、序列化成本高等问题而饱受批评。Java 8 吸收了 Joda-Time 的精华,以一个新的开始为 Java 创建优秀的 API。新的 java.time 中包含了所有关于时钟(Clock),本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法,用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简化了了日期时间和本地化的管理。
Math类
java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型。
abs 绝对值
acos,asin,atan,cos,sin,tan 三角函数
sqrt 平方根
pow(double a,doble b) a的b次幂
log 自然对数
exp e为底指数
max(double a,double b)
min(double a,double b)
random() 返回0.0到1.0的随机数
long round(double a) double型数据a转换为long型(四舍五入)
toDegrees(double angrad) 弧度—>角度
toRadians(double angdeg) 角度—>弧度
BigInteger类
Integer类作为int的包装类,能存储的最大整型值为2^31−1,BigInteger类的数字范围较Integer类的数字范围要大得多,可以支持任意精度的整数。
构造器
BigInteger(Stringval)
常用方法
public BigInteger abs()
public BigInteger add(BigIntegerval)
public BigInteger subtract(BigIntegerval)
public BigInteger multiply(BigIntegerval)
public BigInteger divide(BigIntegerval)
public BigInteger remainder(BigIntegerval)
public BigInteger pow(int exponent)
public BigInteger[] divideAndRemainder(BigIntegerval)
BigDecimal类
一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类。BigDecimal类支持任何精度的定点数。
构造器
public BigDecimal(double val)
public BigDecimal(String val)
常用方法
public BigDecimal add(BigDecimal augend)
public BigDecimal subtract(BigDecimal subtrahend)
public BigDecimal multiply(BigDecimal multiplicand)
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)