黑马程序员_Java基础Day13_String类(Done)

来源:互联网 发布:知乎员工数量 编辑:程序博客网 时间:2024/04/30 01:57

------- android培训、java培训、期待与您交流! ----------


API(Application Programming Interface)是Java给我们对外提供的应用程序接口。即Java定义好并提供出来,给程序员使用的部分。

Java将平时经常遇到、经常使用到的内容进行描述、封装并定义成了对象。String类就是其中之一。



String类

String类是用于描述字符串的类,位于java.lang.String。String类被final修饰,即String类不能有子类。Java中所有的字符串都是此类的实例。

String str = "abc";
String是一个类,str是String类类型的引用,"abc"是一个对象!

字符串最大的特点:字符串一旦被创建,就不可被改变。创建的字符串储存在常量池中。


下面①②结果产生的原因?

class StringDemo {public static void main(String[] args) {String s1 = "abc";String s2 = new String("abc");sop(s1==s2);//false---------------------->①sop(s1.equals(s2));//true---------------->②}public static void sop(Object obj){System.out.println(obj);}}
运行结果为:

其中s1、s2都是String类型的引用。两者由于指向的对象不同,所以内存地址值是不同的。“==”比较两者内存地址值,于是返回的是false。
而equals方法本身是String继承自Object类的方法,在Object类中,equals比较的是引用。但是String类复写了equals方法,比较的是对象中的“内容",即:比较的是字符串是否相同。所以,s1与s2虽然内存地址值不同,指向的不是同一个对象,但是各自对象(字符串)的内容是一样的,都是“abc”,所以②中返回的是true。

上述代码中s1和s2有什么区别呢?
s1在内存中产生了一个对象("abc"),而s2在内存中产生了2个对象(new一个,"abc"一个)。


前面提到,String类适用于描述字符串这类事物的。那么根据面向对象的思想,String类中必然定义并对外提供了一些常用的用于操作字符串的方法。

String类中常见的操作方法:

1,获取

1.1字符串中包含的字符数(字符串的长度):int length()注意:与数组获取长度不同,length在数组中是属性,使用的是arr.lenth;而String类中,获取长度是通过方法完成的,使用的是str.length()

1.2根据位置获取位置上的某个字符:char charAt(int index)注意:如果index是该字符串不存在的角标,则会出现数组角标越界异常(StringIndexOutOfBoundsException)

1.3.1根据字符获取该字符在字符串中的位置:int indexOf(int ch)注意:①indexOf的形参类型是int,因为是通过ASCⅡ查找的。②返回的index是该字符第一次出现在字符串中的位置。③如果传入的ch不存在,返回-1。

1.3.2从fromIndex指定位置开始,获取ch在字符串中出现的位置:int indexOf(int ch,int fromIndex)

1.3.3类似的还有int indexOf(String str)   int indexOf(String str,int fromIndex)   方法,获取的是字符串的位置

1.3.4类似的还有int lastIndexOf(int ch,int fromIndex)等方法,从index位置开始,反向索引字符(字符串)第一次出现的位置

class StringDemo {public static void main(String[] args) {stringGet();}public static void stringGet(){String str = "helloitheima";sop(str.length());//获取字符串长度sop(str.charAt(2));//字符串中2角标位置的字符//sop(str.charAt(100));//发生异常StringIndexOutOfBoundsExceptionsop(str.indexOf('i'));//字符串中'i'字符第一次出现的位置sop(str.indexOf('h',7));//从角标为7的位置开始索引'h'第一次出现的位置sop(str.indexOf('b'));//字符串中没有'b'字符,返回-1sop(str.indexOf("itheima"));//字符串中"itheima"第一次出现的位置sop(str.lastIndexOf('h',7));//从角标为7的位置反向索引,返回第一次出现的位置}public static void sop(Object obj){System.out.println(obj);}}
代码运行结果:

2,判断

2.1字符串中是否包含某一个子串:boolean contains(str)。注意:indexOf(str) 可以索引str在字符串中第一次出现的位置,如果返回-1,则不存在。因此indexOf也可以用于判断指定str是否包含。并且indexOf在判断的同时,还可以返回位置,这点在使用时要加以利用。

2.2字符串中是否有内容: boolean isEmpty() 原理就是判断长度是否为0。注意:""与null是不一样的,前者是一个长度为零的String对象,后者是指向空。

2.3字符串是否是以指定内容开头:boolean startsWith(String str)

2.4字符串是否以指定内容结尾:boolean endsWith(String str)

2.5字符串的内容是否相同:boolean equals(str)。复写了Object类中的equals方法。

2.6判断内容是否相同,并忽略大小写:boolean equalsIgnoreCase(str)。

class StringDemo {public static void main(String[] args) {stringDecide();}public static void stringDecide(){String str = "ArrayDemo.java";sop(str.startsWith("Array"));//判断文件名称是否以Array单词开头sop(str.endsWith(".java"));//判断是否是.java文件sop(str.contains("Demo"));//判断文件名是否包含Demosop(str.equalsIgnoreCase("arraydemo.java"));//忽略大小写比较}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

3,转换

3.1将字符数组转成字符串:

3.1.1构造函数:String(char[])将字符数组转成字符串。String(char[],offset,count)将字符数组中的一部分转成字符串offset是偏移位(起始位置),count是长度(个数)

3.1.2静态方法:static String copyValueOf(char[] data)   static String copyValueOf(char[] data,int offset,int count)

  static String valueOf(char[])

3.2将字符串转成字符数组:char[] toCharArray()

3.3将字节数组转成字符串。同3.1中的方法。

3.4将字符串转成字节数组:byte[] getBytes()

3.5将基本数据类型转成字符串。static String valueOf(基本数据类型)

注意:字符串和字节数组在转换过程中是可以指定编码表的

class StringDemo {public static void main(String[] args) {stringTrans();}public static void stringTrans(){char[] arr = new char[]{'a','b','c','d','e','f','g'};String s = new String(arr,2,5);//将字符数组角标为2长度为5的部分转变成字符串。sop(s);String str = "itheima";char[] ch = str.toCharArray();//将字符串转成字符数组for (int x=0;x<ch.length ;x++ )//遍历字符数组中元素{sop("ch["+x+"]="+ch[x]);}}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

4,替换

使用新字符替换原字符串中的某个字符:String replace(oldchar,newchar)。注意:替换后得到的是新的字符串,原来的字符串并没有被改变。因为字符串一旦被创建就不会被改变。另外,如果被替换的字符并不存在,返回的还是原字符串。

class StringDemo {public static void main(String[] args) {stringReplace();}public static void stringReplace(){String s = "hello world";String s1 = s.replace('l','k');//将原字符串中的l替换成kString str = s.replace("world","itheima");//将原字符串中的world替换成itheimasop("s="+s);sop("s1="+s1);sop("str="+str);}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

5,切割

将原字符串按照规则切割成若干字符串,返回的是字符串数组:String[] split(regex)

class StringDemo {public static void main(String[] args) {stringSplit();}public static void stringSplit(){String s = "zhangsan,lisi,wangwu,zhaoliu";String[] arr = s.split(",");//以","为切割点对原字符串进行切割,并将剩余部分以对应数组的形式返回for (int x=0;x<arr.length ;x++ ){sop("arr["+x+"]="+arr[x]);}}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

6,子串

获取字符串中的一部分:String substring(int beginIndex,int endIndex)。 注意:包含头,不包含尾。

class StringDemo {public static void main(String[] args) {stringSub();}public static void stringSub(){String str = "hello itheima";String s1 = str.substring(3);//从角标为3的位置开始获取子串。String s2 = str.substring(6,13);//获取角标从6至13位置的字符串。注意,包含头,不包含尾。//String s3 = str.substring(6,20);//出现字符串中没有的角标位置,会出现StringIndexOutOfBoundsException(字符串交表越界)异常。sop("s1="+s1);sop("s2="+s2);}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

7,其他常见操作(转换,去除空格,比较)

7.1将字符串转化成大写或者小写:String toUpperCase();String toLowerCase()。

7.2取出字符串两端的多于空格:String trim()。

7.3对两个字符串进行自然顺序的比较:int compareTo(String str)。将原String s0与传入的String str进行自然顺序的比较。如果s0在str前,返回负数;s0与str相同,返回0;s0在str后,返回正数。(其实返回的是第一次出现不同字符时,两字符ASCⅡ数值的差)

class StringDemo {public static void main(String[] args) {stringOthers();}public static void stringOthers(){String s = "   Hello ItheiMa   ";//两端有空格,字母大小写均有String s1 = "hello world";sop("("+s.toUpperCase()+")");//转换成大写sop("("+s.toLowerCase()+")");//转换成小写sop("("+s.trim()+")");//去除原字符串两端空格sop(s.compareTo(s1));}public static void sop(Object obj){System.out.println(obj);}}
运行结果:

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

class StringTestToTrim {public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) {String str = "   hello itheima   ";//两端有空格的字符串String str1 = "       ";//考虑全都是空格的特殊情况String s = toTrim(str);String s1 = toTrim(str1);sop("原字符串:("+str+")");sop("现字符串:("+s+")");sop("-------------------------------");sop("原字符串:("+str1+")");sop("现字符串:("+s1+")");}public static String toTrim(String str){int postart = 0;//定义两个指针,用于标识开始与末尾位置int posend = str.length()-1;for (;postart<=posend && str.charAt(postart)==' ' ;postart++ ){}//满足头指针不大于尾指针,且头指针位置为空格时,头指针向后移动for (;postart<=posend && str.charAt(posend)==' ' ;posend-- ){}//满足头指针不大于尾指针,且尾指针位置为空格时,尾指针向前移动return str.substring(postart,posend+1);//返回最终头指针和尾指针之间的子串,由于包含头不包含尾,所以尾指针需要+1}}
运行结果:

2.将字符串指定范围处进行镜像反转。
class StringTestReverse {public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) {String str = "hello itheima";sop("原来字符串:("+str+")");sop("现字符串一:("+reverse(str)+")");sop("现字符串二:("+reverse(str,3,9)+")");}public static String reverse(String str,int beginIndex,int endIndex){char[] chr = str.toCharArray();//将字符串转换成字符数组reverseArray(chr,beginIndex,endIndex);//将数组指定范围反转return String.valueOf(chr);//再将字符数组转成字符串}private static String reverse(String str)//重载reverse方法{return reverse(str,0,str.length());}private static void reverseArray(char[] chr,int beginIndex,int endIndex)//定义数组指定范围反转方法{for (int postart=beginIndex,posend=endIndex-1;postart<posend ;postart++,posend-- ){swap(chr,postart,posend);}}private static void swap(char[] chr,int a,int b)//换位置操作{char temp = chr[a];chr[a] = chr[b];chr[b] = temp;}}
运行结果:

3.定义方法,计算长字符串中有多少个短字符串
class  StringTestSubCount{public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) {String str = "hello itheima";String s0 = "he";sop(str+"中,有"+subCount(str,s0)+"个"+s0+"字符");}private static int subCount(String str,String target){int count = 0;//定义计数器,并初始化为0for (int pos=0;(pos=str.indexOf(target,pos))!=-1 ; )//遍历判断是否包含target字符串{pos += target.length();count++;}return count;}}

运行结果:

4.获取两字符串的最长公共子串。
class  StringTestGetMaxSub{public static void sop(Object obj){System.out.println(obj);}public static void main(String[] args) {String s1 = "hello itheima";String s2 = "helloworld";sop(s1+"与"+s2+"的最长公共子串为:"+getMaxSub(s1,s2));}private static String getMaxSub(String s1,String s2){String longer = (s1.length()>s2.length())?s1:s2;//锁定长字符串和短字符串String shorter = (longer==s1)?s2:s1;for (int x=0;x<shorter.length() ;x++ ){for (int start=0,end=shorter.length()-x;end!=(shorter.length()+1) ; start++,end++){String max = shorter.substring(start,end);if (longer.contains(max))//判断长字符串是否包含段字符串的子串return max;}}return "";}}
运行结果:



StringBuffer类

String类中,字符串一旦初始化就不能被改变。StringBuffer可以用于对字符串进行修改。

StringBuffer是字符串缓冲区,是一个容器。长度可变,可以直接操作多个数据类型,最终通过toString方法变成字符串。

StringBuffer常见操作:

1,存储

StringBuffer append():将指定的数据作为参数添加到已有数据的结尾处。

StringBuffer insert(index,数据):可以将数据插入到指定index位置。注意:如果index值是不存在的,会发生StringIndexOutOfBoundsException异常

class StringBufferDemo {public static void sop(Object obj){System.out.println(obj);}public static void add(){StringBuffer sb = new StringBuffer();StringBuffer sb1 = sb.append("007");sop("sb="+sb);sop("sb1="+sb1);sop("sb==sb1?"+(sb==sb1));sop("--------------------");sop("在角标1位置插入kk后变为:"+sb.insert(1,"kk").toString());}public static void main(String[] args) {add();}}
运行结果:

观察结果,可知sb和sb1指向的是同一个对象,即经过操作后得到的是原对象。

2,删除

StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end。

StringBuffer deleteCharAt(index):删除指定位置的字符。

class StringBufferDemo {public static void sop(Object obj){System.out.println(obj);}public static void delete(){StringBuffer sb = new StringBuffer("abcdefg");sb.delete(1,3);//删除角标1至3之间的部分,包含头,不包含尾。//sb.delete(0,sb.length());//清空缓冲区sop(sb);sb.deleteCharAt(2);//删除角标2位置上的字符sop(sb);}public static void main(String[] args) {delete();}}
运行结果:

3,获取

char charAt(int index):根据索引获取字符。

int indexOf(String str):获取字符串出现的位置。

int length():获取长度。

String substring(int start,int end)

4,修改(替换)

StringBuffer replace(int start,int end,String str)

void setCharAt(int index,char ch)

class StringBufferDemo {public static void sop(Object obj){System.out.println(obj);}public static void update(){StringBuffer sb = new StringBuffer("hello world");sb.replace(6,11,"itheima");//替换角标6至11位置的字符串sop(sb);sb.setCharAt(6,'I');//将角标6位置的字符换成Isop(sb);}public static void main(String[] args) {update();}}
5,反转

StringBuffer reverse()

6,

将缓冲区中的指定数据存储到指定字符数组中:void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin)。注意:角标不能越界。

class StringBufferDemo {public static void sop(Object obj){System.out.println(obj);}public static void other(){StringBuffer sb = new StringBuffer("abcdef");char[] chs = new char[4];sb.getChars(1,4,chs,1);for (int x=0;x<chs.length ;x++ ){sop("chs["+x+"]="+chs[x]+";");}}public static void main(String[] args) {other();}}
运行结果:



StringBuilder类

JDK1.5版本后出现的StringBuilder。

StringBuilder与StringBuffer的不同:

①StringBuffer是线程同步的,用于多线程中;StringBuilder是线程不同步的,如果在多线程中使用需要自己加锁。

②StringBuilder虽然线程不同步,但是效率更高。

建议使用StringBuilder

Java升级一般围绕三个方面:
①提高效率;
②简化书写;
③提高安全性。


基本数据类型对象包装类

byte Byte

short Short

int Integer

long Long

boolean Boolean

float Float

double Double

char Character


基本数据类型对象包装类最常见作用:就是用基本数据类型和字符串类型之间转换。

基本数据类型转成字符串:

1.基本数据类型+"";如:123+""

2.基本数据类型.toString(基本数据类型值);

字符串转成基本数据类型。

xxx a = Xxx.parseXxx(String)。如:int a = Integer.parseInt("123")      boolean b = Boolean.parseBoolean("true")

十进制转成其他进制。

toBinaryString();toHexString();toOctalString();

其他进制转成十进制。

Integer.parseInt(String s,radix)


JDK1.5版本后的新特性

Integer x = new Integer(4);Integer x = 4;
这两种写法都可以,这就是自动装箱。并且x可以直接进行运算,如:x = x+2 。x先进行了自动拆箱,变成int类型与2进行加法运算,然后将计算结果进行装箱赋给x。拆箱过程中调用了x.intValue()方法


Integer m = 128;Integer n = 128;//m==n 吗? falseInteger x = 127;Integer y = 127;//x==y吗? true
因为x和y指向了同一个对象,因为当数值在byte范围内时,对于新特性,如果该数值已经存在,不会再开辟新的空间。



原创粉丝点击