8、String类
8.1字符串特点
字符串是一个特殊的对象
字符串最大的特点:字符串一旦初始化就不可以被改变。
8.2区别字符变量
String s1 = “abc”;
String s2 = new String(“abc”);
String s3 = “abc”;
s1==s2;false//一个对象不等于两个对象
s1==s3;true//指向同一变量
s1.equals(s2);true//变量的内容相同
有什么区别?
1、 s1 是一个类类型变量,“abc”是一个对象
2、 String类复写了Object类中equals方法,该方法用于判断字符串内容是否相同。
3、 s1在内存中有一个对象。
4、 s2在内存中有两个对象。
8.3String 类的声明:
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence
8.4String类的常用方法(会用)
8.4.1获取
a) 字符串中的包含的字符数,也就是字符串的长度。
int length():获取长度。(数组的长度是属性,没有括号)
b) 根据位置获取位置上某个字符。
char charAt(int index):当访问的字符串中不存在的脚标时会发生StringIndexOutOfBoundsException异常。
c) 根据字符获取该字符在字符串中位置。
int indexOf(int ch):返回的是ch在字符串中第一次出现的位置。“ch”在这里为ASCII码值,也可以用字符。当没有找到字符是返回的是“-1”
int indexOf(int ch, int fromIndex) :从fromIndex指定位置开始,获取ch在字符串中出现的位置。
int indexOf(String str):返回的是子串str在字符串中第一次出现的位置。
int indexOf(String str, int fromIndex) :从fromIndex指定位置开始,获取str在字符串中出现的位置。
int lastIndexOf(int ch) :(反向索引见下表)
| lastIndexOf |
| lastIndexOf |
| lastIndexOf |
| lastIndexOf |
8.4.2判断。
d) 字符串中是否包含某一个子串。
boolean contains(str)://判断文件名称是否包含子串
特殊之处:indexOf(str):可以索引str第一次出现位置,如果返回-1.表示该str不在字符串中存在。所以,也可以用于对指定字符串的判断是否包含。
if(str.indexOf("aa")!=-1)而且该方法即可以判断,又可以获取出现的位置。
e) 字符中是否有内容。
boolean isEmpty(): 原理就是判断长度是否为0.
f) 字符串是否是以指定内容开头。
boolean startsWith(str);//判断文件名是否以开头
g) 字符串是否是以指定内容结尾。
boolean endsWith(str);//判断文件的扩展名“.*”
h) 判断字符串内容是否相同。复写了Object类中的equals方法。
boolean equals(str);
i) 判断内容是否相同,并忽略大小写。
boolean equals IgnoreCase();
8.4.4转换。
j) 将字符数组转成字符串。
构造函数:
String(char[])
String(char[],offset,count):字符数组中的一部分转成字符串。
参数说明:
“char[]”:字符数组;“offset”:起始位置;“count”:长度。
静态方法:
static String copyValueOf(char[]);
返回指定数组中表示该字符序列的 String。
static String copyValueOf(char[] data, int offset, int count)
返回指定数组中表示该字符序列的 String。
k) 将字符串转成字符数组。
char[] toCharArray():
将此字符串转换为一个新的字符数组。
l) 将字节数组转成字符串。
String(byte[])
String(byte[],offset,count):将字节数组中的一部分转成字符串。
m) 将字符串转成字节数组。
byte[] getBytes():
使用指定的字符集将此String 编码为 byte 序列,并将结果存储到一个新的byte 数组中。
特殊:字符串和字节数组在转换过程中,是可以指定编码表的。
n) 将基本数据类型转成字符串。
static String valueOf(int)
static String valueOf(double)
返回 int、double 参数的字符串表示形式。
8.4.5替换
String replace(char oldchar,char newchar);
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。如果要替换的字符串不存在,返回的还是原来的串。也可以字符串替换。
8.4.6切割
String[] split(regex);
根据给定正则表达式的匹配拆分此字符串。返回一个字符串数组。
8.4.7子串
获取字符串中的一部分。
public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
public String substring(int beginIndex,int endIndex)
返回一个新字符串,它是此字符串的子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
8.4.8转换,去除空格,比较。
o) 将字符串转成大写或则小写。
String toUpperCase();
String toLowerCase();
p) 将字符串两端的多个空格去除。
String trim();
q) 对两个字符串进行自然顺序的比较。
public int compareTo(String anotherString)
如果参数字符串等于此字符串,则返回值 0
;如果此字符串按字典顺序小于字符串参数,则返回一个小于0
的值;如果此字符串按字典顺序大于字符串参数,则返回一个大于0
的值
8.5String方法练习:
8.5.1、模拟一个trim方法,去除字符串两端的空格。
思路:
1,判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。
结尾处判断空格也是如此。
2,当开始和结尾都判断到不是空格时,就是要获取的字符串。
8.5.2、将一个字符串进行反转。
将字符串中指定部分进行反转,"abcdefg";abfedcg
思路:
1,曾经学习过对数组的元素进行反转。
2,将字符串变成数组,对数组反转。
3,将反转后的数组变成字符串。
4,只要将或反转的部分的开始和结束位置作为参数传递即可。
示例代码:
class StringTest
{
public static void sop(String str)//输出封装函数
{
System.out.println(str);
}
public static void main(String[] args)
{
String s = " ab cd ";
sop("("+s+")");//去除空格前
s = myTrim(s); //调用函数去除空格
sop("("+s+")");//去除空格后
sop("("+reverseString(s)+")"); //调用函数反转
}
public static String reverseString(String s,int start,int end)//反转
{
//字符串变数组。
char[] chs = s.toCharArray();
//反转数组。
reverse(chs,start,end);
//将数组变成字符串。
return new String(chs);
}
public static String reverseString(String s)
{
return reverseString(s,0,s.length());
}
private static void reverse(char[] arr,int x,int y)//反转数组
{
for(int start=x,end=y-1; start<end ; start++,end--)
{
swap(arr,start,end);
}
}
private static void swap(char[] arr,int x,int y)//交换元素
{
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static String myTrim(String str)//去除两边空格方法
{
int start = 0,end = str.length()-1;
while(start<=end && str.charAt(start)==' ')//遇空自增
start++;
while(start<=end && str.charAt(end)==' ') //遇空自减
end--;
return str.substring(start,end+1);//返回切割的子串
}
}
8.5.3、获取一个字符串在另一个字符串中出现的次数。
思路:
1,定义个计数器。
2,获取kk第一次出现的位置。
3,从第一次出现位置后剩余的字符串中继续获取kk出现的位置。
每获取一次就计数一次。
4,当获取不到时,计数完成。
class StringTest2//方式一
{
public static int getSubCount(String str,String key)
{
int count = 0;
int index = 0;
while((index=str.indexOf(key))!=-1)//取第一个符合的
{
sop("str="+str);
str = str.substring(index+key.length());//子串
count++;
}
return count;
}
//方式二。
public static int getSubCount_2(String str,String key)
{
int count = 0;
int index = 0;
while((index= str.indexOf(key,index))!=-1)
{
sop("index="+index);
index = index + key.length();//脚标
count++;
}
return count;
}
public static void main(String[] args)
{
String str = "kkabkkcdkkefkks";
//sop("count====="+str.split("kk").length);不建议使用。
sop("count="+getSubCount_2(str,"kk"));
}
public static void sop(String str)
{
System.out.println(str);
}
}
8.5.4、获取两个字符串中最大相同子串。
第一个动作:将短的那个串进行长度一次递减的子串打印。
"abcwerthelloyuiodef"
"cvhellobnm"
思路:
1,将短的那个子串按照长度递减的方式获取到。
2,将每获取到的子串去长串中判断是否包含,
如果包含,已经找到!。
class StringTest3
{
public static String getMaxSubString(String s1,String s2)
{
String max = "",min = "";//判断长短串
max = (s1.length()>s2.length())?s1: s2;
min = (max==s1)?s2: s1;
sop("max="+max+"...min="+min);
for(int x=0; x<min.length(); x++)
{
for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++)
{
String temp = min.substring(y,z);
sop(temp);
if(max.contains(temp))//if(s1.indexOf(temp)!=-1)
return temp;
}
}
return "";
}
public static void main(String[] args)
{
String s1 = "ab";
String s2 = "cvhellobnm";
sop(getMaxSubString(s2,s1));
}
public static void sop(String str)
{
System.out.println(str);
}
}
8.5.5、对字符串中字符进行自然顺序排序。
思路:
1,字符串变成字符数组。
2,对数组排序,选择,冒泡,Arrays.sort();
3,将排序后的数组变成字符串。
"12 0 99 -7 30 4 100 13"
要求对字符串中的数值进行排序。生成一个数值从小到大新字符串。
"-7 0 4 12 13 30 99 100"
8.6StringBuffer
8.6.1、StringBuffer是字符串缓冲区。
String一旦定义不能被修改;StringBuffer可以对字符串进行修改。字符串的组成原理就是通过该类实现的,StringBuffer可以对字符串内容进行增删,StringBuffer是一个容器(容器:存储、删除、获取、修改CURD:C create U update R read D delete)很多方法与String相同。
8.7StringBuffer特点:
1,长度是可变化的。
2,可以直接操作多个数据类型。
3,最终会通过toString方法变成字符串。
8.7.1StringBuffer方法声明:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
8.8StringBuffer的常用方法
8.8.1、存储
StringBuffer append(数据类型的参数):将指定的数据添加到已有数据的结尾处。其中支持基本数据类型:除了short和byte可以被int提升。
StringBuffer insert(index,数据):可以将数据插入到指定index位置。返回原来的缓冲区。不可脚标越界。最终变成字符串。
8.8.2,删除。
StringBuffer delete(int start,int end):删除缓冲区中的数据,包含start,不包含end。
StringBuffer deleteCharAt(int index):删除指定位置的字符。
8.8.3,获取。
char charAt(int index)
int indexOf(String str)
int lastIndexOf(String str)
int length()
String substring(int start, int end) :返回String类型,不是StringBuffer类型。
8.8.4,修改。
StringBuffer replace(start,end,string);
void setCharAt(int index, char ch) ;只替换,不返回
8.8.5,反转。
StringBuffer reverse();
8.8.6,将缓冲区中指定数据存储到指定字符数组中。
含头不含尾。
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
示例程序:
class StringBufferDemo
{
public static void main(String[] args)
{
//method_update();
StringBuilder sb = new StringBuilder("abcdef");
char[] chs = new char[6];
sb.getChars(1,4,chs,1);//将
for(int x=0; x<chs.length; x++)
{
sop("chs["+x+"]="+chs[x]+";");
}
draw(3,6);
draw(8,9);
// StringBuilder sb1 = new StringBuilder();
// sb1.append(new Demo()).append(new Demo());
// sop("sb1="+sb1);
}
public static void method_update()
{
StringBuffer sb = new StringBuffer("abcde");
// sb.replace(1,4,"java");//结果为ajavae
sb.setCharAt(2,'k');
sop(sb.toString());
}
public static void method_del()
{
StringBuffer sb = new StringBuffer("abcde");//已初始化就有数据
// sb.delete(1,3);//删掉bc
//sb.delete(0,sb.length());//清空缓冲区。
//sb.delete(2,3);//删掉c
sb.deleteCharAt(2);//删除指定位置脚标元素
sop(sb.toString());//字符串形式输出
}
public static void method_add()
{
StringBuffer sb = new StringBuffer();
//方法调用链:这个方法返回来的还是本类对象,所以还可以调用本类对象
//sb.append("abc").append(true).append(34);
// StringBuffer sb1 = sb.append(34);
// sop("sb==sb1:"+(sb==sb1));//结果为true
sb.insert(1,"qq");
sop(sb.toString());//abctrue34
//sop(sb1.toString());
}
public static void sop(String str)
{
System.out.println(str);
}
public static void draw(int row,int col)
{
StringBuilder sb = new StringBuilder();
for(int x=0; x<row; x++)
{
for(int y=0; y<col; y++)
{
sb.append("*");
}
sb.append("\r\n");
}
sop(sb.toString());
}
}
8.9JDK1.5升级三个因素:
1,提高效率。StringBuilder
2,简化书写。
3,提高安全性。
JDK1.5出现一个StringBuilder,区别是StringBuffer安全的,是线程同步的,StringBuilder是不安全的,是线程非同步的,单线程。以后开发,建议