String类
创建字符串
- String(char a[])方法
char a[] ={'g','o','o,'d'};
String s = new String(a);
等价于:String s= new String("good");
- String(char a[],int offset, int length)方法
提取字符数组a中的一部分创建一个字符串对象。参数offset表示开始截取字符串的位置,length表示截取字符串的长度。
char a[] ={'s','t','u','d','e','n','t'};
String s =new String(a,2,4);
等价于:String s= new String("uden");
连接字符串
连接多个字符串
使用“+”运算符可实现连接多个字符串的功能,并且产生一个String对象。

连接其他数据类型
字符串也可以同其他基本数据类型进行连接。如果将字符串同这些数据类型进行连接,会将字符直接转化成字符串。
如下图:booktime和practice都不是Sting字符,当与字符串连接时,会自动调用toString()方法,将其转换成字符串形式。
只要“+”运算符的一个操作数是字符串,编译器就会将另一个操作数转换成字符串形式,所以应谨慎使用。

获取字符串信息
获取字符串长度
使用String类的length()方法可获取声明的字符串对象的长度。str.length();其中str为字符串对象。
String str ="We are students";
int size =str.length();
字符串查找
- indexOf(String s)该方法返回参数字符串s在指定字符串中首次出现的索引位置。如果没有检索到字符串s,该方法返回值是-1。
str.indexOf(substr)
str:任意字符串对象;sbustr:要搜索的字符串。

- lastIndexOf(String str)该方法用于返回指定字符串最后一次出现的索引位置。当调用字符串的lastIndexOf()方法时,会从当前字符串的开始位置检索参数字符串str,并将最后一次出现str的索引位置返回。如果没有检索到字符串str,则返回-1。
str.lastIndexOf(substr);
str:任意字符串对象;sbustr:要搜索的字符串。

获取指定索引位置的字符
使用charAt()方法可将指定索引处的字符返回,语法如下:
str.charAt(int index)
str:任意字符串对象;index:整型值,用于指定要返回字符的下标。

字符串操作
获取字符串
通过substring()方法可对字符串进行截取。
- substring(int beginIndex),语法:
str.substring(int beginIndex)

- substring(int beginIndex,int endIndex)
str.substring(int beginIndexint,endIndex)
beginIndex - 起始索引(包括),注意从0开始。
endIndex - 结束索引(不包括)。

去除空格
trim()方法返回字符串副本,忽略前导空格和尾部空格(不包括中间空格)。语法如下:
str.trim()

字符串替换
replace()方法可以实现将指定字符或字符串换成新的字符或字符串。语法:
str.repalace(char oldChar,char newChar)

判断字符串的开始与结尾
startsWith()方法与endsWith()方法分别判断字符串是否以指定的内容开始或结束。返回值都为boolean型。
str.startsWith(String prefix),其中prefix是指作为前缀的字符。
str.endsWitch(String suffix),suffix指作为后缀的字符。

判断字符串是否相等
比较字符串内容是否相等,可以使用equals()和equalsIgnoreCase()方法。如果两个字符串,字符和长度相等,可以使用equals()方法,相等的话返回true;
str.equals(String Otherstr)
str和Otherstr是参与比较的两个对象。
equalsIgnoreCase()方法是在忽略了大小写的情况下比较两个字符串是否相等,返回类型也是boolean类型。
str.equalsIgnoreCase(String Otherstr)

判断字符串是否相等
toLowerCase()方法可将字符串中的所有字符从大写字母改成小写字母:
str.toLowerCase()
toUpperCase()方法可将字符串中所有字符的小写字母改成大写字母:
str.toUpperCase()

字符串分割
- 使用split()方法可以使字符串按指定的分割字符或字符串对内容进行分割,并将分割后的结果存放在字符串数组中。
str.split(String sign) 其中,sign为分割字符串的分隔符,也可以是正则表达式。

- split(String sign,int limit),该方法根据给定的分隔符对字符串进行拆分,并限定拆分的次数。
str.split(String sign,int limit)
limit表示限制分割的次数。

格式化字符串
时间和日期字符串格式化
1. 日期格式化
Date date = new Date();
String s =String.formate("%te",date);


2. 时间格式化
format()格式不仅可以完成日期的格式化,也可以实现时间的格式化。时间格式化可以将时间精确到时,分,秒,毫秒。


3. 格式化常见的日期时间组合
格式化日期与时间的转换符定义了各种日期时间组合的格式:


正则表达式
正则表达式通常用于判断语句中,用来检查某一字符串是否满足于某一格式。

示例:
[^456]: 代表4、5、6之外的任意字符
[a-r]:代表a~r中的任何一个字母
[a-zA-Z]:表示任何一个英文字母
[a-e[g-z]]:表示a到e,或g到z中的任何一个字母(并运算)
[a-0&&[def]]:代表字母d、e、f(交运算)
[a-d&&[^bc]]:代表字母a、b(差运算)


网友评论