字符串相关类

String类

概述

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是一个final类,代表不可变的字符序列
  • 字符串是不可变的。一个字符串对象一旦被配置,其内容是不可变的。

字符串对象操作

  • public int length():返回字符串的长度
  • public char charAt(int index):返回指定index位置的字符,index从0开始
  • public boolean equals(Object anObject):比较两个字符串是否相等。相等为true,否则为false
  • public int compareTo(String anotherString)
  • public int indexOf(String s):返回字符串在当前字符串首次出现的位置,若没有,返回-1
  • public int indexOf(String s ,int startpoint):返回字符串从当前字符串startpoint位置开始,首次出现的位置
  • public int lastIndexOf(String s):返回字符串在当前字符串最后一次出现的位置,若没有,返回-1
  • public int lastIndexOf(String s ,int startpoint):返回字符串从当前字符串startpoint位置开始,最后一次出现的位置
  • public boolean startsWith(String prefix):判断当前字符串是否以prefix开始
  • public boolean endsWith(String suffix):判断当前字符串是否以suffix结束
  • public boolean regionMatches(int firstStart,String other,int otherStart ,int length):判断当前字符串从firstStart开始的子串与另一字符串other从otherStart开始,length长度的字符串是否相等

字符串对象修改

  • public String substring(int startpoint):返回从startpoint开始到结束的字符串
  • public String substring(int start,int end):返回从startpoint开始到end结束的字符串
  • pubic String replace(char oldChar,char newChar):将字符串中oldChar全部替换为newChar
  • public String replaceAll(String old,String new):将原字符串old替换为新字符串new
  • public String trim():去除当前字符串中首和尾的空格
  • public String concat(String str):连接当前字符串和str
  • public String[] split(String regex):将原有字符串以regex分割,返回String类型的数组

练习

练习1:模拟一个trim方法,去除字符串两端的空格。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class TestString {
public static void main(String[] args) {
System.out.println(myTrim(" 小新不吃 蔬菜 "));

}

public static String myTrim(String str){
int start = 0;
int end = str.length() - 1;
while (start < end && str.charAt(start) == ' '){
start ++;
}
while (start < end && str.charAt(end) == ' '){
end --;
}
return str.substring(start, end + 1);
}
}

练习2:将一个字符串进行反转。将字符串中指定部分进行反转。比如将“abcdefg”反转为”abfedcg”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class TestString {
public static void main(String[] args) {
System.out.println(reverseString("小123新",1,3));
System.out.println(reverseString2("小123新",1,3));
}
/*
方法一
*/
public static String reverseString(String str, int start, int end){
return reverseArray(str.toCharArray(),start,end);
}
public static String reverseArray(char[] c, int start, int end){
for (int i = start, j = end; i < j; i++, j--){
char temp = c[i];
c[i] = c[j];
c[j] = temp;
}
return new String(c);
}
/*
方法二
*/
public static String reverseString2(String str, int start, int end){
String str1 = str.substring(0,start);
for (int j = end; j >= start; j--){
char c = str.charAt(j);
str1 += c;
}
str1 += str.substring(end + 1);
return str1;
}
}

练习3:获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab”中出现的次数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestString {
public static void main(String[] args) {
System.out.println(getTimes("abkkcadkabkebfkabkskab", "ab"));
}
/*
获取一个字符串在另一个字符串中出现的次数。比如:获取“ab”在 “abkkcadkabkebfkabkskab”中出现的次数
*/
public static int getTimes(String str1, String str2){
int count = 0;
int len;
while ((len = str1.indexOf(str2)) != -1){
count ++;
str1 = str1.substring(len + 1);
}
return count;
}
}

练习4:获取两个字符串中最大相同子串。比如:str1 = “abcwerthelloyuiodef”;str2 = “cvhellobnm”。提示:将短的那个串进行长度依次递减的子串与较长的串比较。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.ArrayList;
import java.util.List;

public class TestString {
public static void main(String[] args) {
List<String> list = getMaxSubString("abcwerthelloyuiodef", "abcwevhellobnm");
System.out.println(list);
}
/*
获取两个字符串中最大相同子串。比如:str1 = "abcwerthelloyuiodef";str2 = "cvhellobnm"。
提示:将短的那个串进行长度依次递减的子串与较长的串比较。
*/
public static List<String> getMaxSubString(String str1, String str2){
String max = (str1.length() > str2.length()) ? str1 : str2;
String min = (str1.length() < str2.length()) ? str1 : str2;
int len = min.length();
List<String> list = new ArrayList<>();
for (int i = 0; i < len; i++){
for (int x = 0, y = len - i; y <= len; x++, y++){
String str = min.substring(x, y);
if (max.contains(str)){
list.add(str);
}
}
if (list.size() != 0){
return list;
}
}
return null;
}
}

练习5:对字符串中字符进行自然顺序排序。提示:

  1. 字符串变成字符数组。
  2. 对数组排序,选择,冒泡,Arrays.sort();
  3. 将排序后的数组变成字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.Arrays;

public class TestString {
public static void main(String[] args) {
System.out.println(Sort("fgebdca"));
}
/*
练习5:对字符串中字符进行自然顺序排序。提示:
1. 字符串变成字符数组。
2. 对数组排序,选择,冒泡,Arrays.sort();
3. 将排序后的数组变成字符串。
*/
public static String Sort(String str){
char[] c = str.toCharArray();
Arrays.sort(c);
return new String(c);
}
}

字符串与基本数据类型相互转化

  • 字符串转换为基本数据类型

    • 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)可由参数的相应类到字符串的转换

字符串与字节数组相互转化

  • 字符串转换为字节数组

    • public byte[] getBytes() 方法使用平台默认的字符编码,将当前字符串转化为一个字节数组。
    • public byte[] getBytes(String charsetName) 使用参数指定字符编码,将当前字符串转化为一个字节数组。
  • 字节数组转换为字符串

    • String(byte[])用指定的字节数组构造一个字符串对象。
    • String(byte[],int offset,int length) 用指定的字节数组的一部分,即从数组起始位置offset开始取length个字节构造一个字符串对象。

字符串与字符数组相互转化

  • 字符串转换为字符数组

    • 将字符串中的全部字符存放在一个字符数组中的方法:public char[] toCharArray()
  • 字符数组转换为字符串

    • String 类的构造方法:String(char[])String(char[],int offset,int length) 分别用字符数组中的全部字符和部分字符创建字符串对象

StringBuffer类

概述

  • java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删。
  • 很多方法与String相同,但StingBuffer是可变长度的。
  • StringBuffer是一个容器。
  • StringBuffer类有三个构造方法:
    • StringBuffer()初始容量为16的字符串缓冲区
    • StringBuffer(int size)构造指定容量的字符串缓冲区
    • StringBuffer(String str)将内容初始化为指定字符串内容

常用方法

  • 添加

    • StringBuffer append(String s)
    • StringBuffer append(int n)
    • StringBuffer append(Object o)
    • StringBuffer append(char n)
    • StringBuffer append(long n)
    • StringBuffer append(boolean n)
  • 插入

    • StringBuffer insert(int index, String str)
  • 反转

    • public StringBuffer reverse()
  • 删除

    • StringBuffer delete(int startIndex, int endIndex)
    • public char charAt(int n )
  • 修改

    • public void setCharAt(int n ,char ch)
  • 替换

    • StringBuffer replace( int startIndex ,int endIndex, String str)
  • 返回索引

    • public int indexOf(String str)
  • 返回子串

    • public String substring(int start,int end)
  • 返回长度

    • public int length()

StringBuilder类

  • StringBuilder 和 StringBuffer 非常类似,均代表可变的字符序列,而且方法也一样
    • String:不可变字符序列
    • StringBuffer:可变字符序列、效率低、线程安全
    • StringBuilder(JDK1.5):可变字符序列、效率高、线程不安全

日期类

System类

System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。此方法适于计算时间差。

计算世界时间的主要标准有:

  • UTC(Universal Time Coordinated)
  • GMT(Greenwich Mean Time)
  • CST(Central Standard Time)

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是时间标准。

SimpleDateFormat类

Date类的API不易于国际化,大部分被废弃了,java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类。

  • 它允许进行格式化(日期—>文本)、解析(文本>日期)

  • 格式化:

    • SimpleDateFormat() :默认的模式和语言环境创建对象
    • public SimpleDateFormat(String pattern):该构造方法可以用参数pattern指定的格式创建一个对象
    • 该对象调用:**public String format(Date date)**:方法格式化时间对象date
  • 解析:

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

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)

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(String val)
  • 常用方法

    • public BigInteger abs()
    • public BigInteger add(BigInteger val)
    • public BigInteger subtract(BigInteger val)
    • public BigInteger multiply(BigInteger val)
    • public BigInteger divide(BigInteger val)
    • public BigInteger remainder(BigInteger val)
    • public BigInteger pow(int exponent)
    • public BigInteger[] divideAndRemainder(BigInteger val)

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)

面试题

  • String s = new String(“xyz”); 创建了几个String Object
    答:两个,一个字符对象,一个字符对象引用对象

  • Math.round(11.5)等于多少? Math.round(-11.5)等于多少
    答: Math.round(11.5)==12;Math.round(-11.5)==-11;round方法返回与参数最接近的长整数,参数加1/2后求其floor

  • 是否可以继承String类
    答:String类是final类,故不可以继承

  • String与StringBuffer的区别。
    答:String 的长度是不可变的,StringBuffer的长度是可变的。如果你对字符串中的内容经常进行操作,特别是内容要修改时,那么使用StringBuffer,如果最后需要String,那么使用StringBuffer的toString()方法。