黑马程序员---Java基础--13天(String类)

来源:互联网 发布:淘宝自己拍图防盗 编辑:程序博客网 时间:2024/05/20 06:31

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

1.String(概述)
class StringDemo {public static void main(String[] args) {String s1 = "abc";//s1是一个类类型变量,"abc"是一个对象.//字符串最大特点:一旦被初始化就不可以被改变.String s2 = new String("abc")//s1和s2有什么区别?//s1在内存中有一个对象.//s2在内存中有两个对象.(new,"abc")System.out.println(s1==s2);flase.System.out.println(s1.equals(s2));true.//String类复写了Object类中equals方法.//该方法用于判断字符串是否相同.}}


2.String(常见功能-获取和判断)
3.String(常见功能-转换)
4.String(常见功能-切割和替换)
5.String(常见功能-比较和去除空格)
/*String类适用于描述字符串事物.那么他就提供了多个方法对字符串进行操作.常见的操作有哪些?"abcd"1.获取.1.1字符串中的包含的字符数,也就是字符串的长度.int length():获取长度.1.2根据位置获取位置上某个字符.char charAt(int index):1.3根据字符获取该字符在字符串中位置.int indexOf(int ch):返回的是ch在字符串中第一次出现的位置.int indexOf(int ch,int fromIndex):从fromIndex指定位置开始,获取ch在字符串中出现的位置.int indexOf(String str):返回的是str在字符串中第一次出现的位置.int indexOf(int ch,int fromIndex):从fromIndex指定位置开始,获取str在字符串中出现的位置.int lastIndexOf(int ch):反向索引.2.判断.2.1字符串中是否包含某一个子串.boolean contains(str):特殊之处:indexOf(str):可以索引str第一次出现的位置,如果返回-1,表示该str不在字符串中存在.所以,也可以用于对指定判断是否包含.if(str.indexOf("aa")!=-1)而且该方法即可以判断,又可以获取出现的位置.2.2 字符串中是否有内容.boolean isEmpty():原理就是判断长度是否为0.2.3 字符串是否是以指定内容开头.boolean startsWith(str);2.4 字符串是否是以指定内容结尾.boolean endsWith(str);2.5 判断字符串内容是否相同.复写了Object类中的equals方法.boolean equals(str);2.6 判断内容是否相同,并忽略大小写.boolean equalsIngoreCase();3.转换3.1 将字符数组转成字符串.构造函数:String(char[]) String(char[],offset,count):将字符数组中的一部分转成字符串.静态方法:static String copyValueOf(char[]);static String copyValueOf(char[] data,int offset,int count)static String ValueOf(char[])3.2 将字符串转成字符数组.**char[] toCharArray();3.3 将字节数转成字符串.String(byte[])String(byte[],offset,count):将字节数组中的一部分转成字符串.3.4 将字符串转成字节数组.byte[] getBytes();3.5 将基本数据类型转成字符串.static String valueOf(int)static String valueOf(double)//3+"";//String.valueOf(3);特殊:字符串和字节数组在转换过程中,是可以指定编码表的.4.替换String replace(oldchar,newchar);5.切割String[] split(regex);6.子串String substring(begin);String substring(begin,end);7.转换.取出空格,比较.7.1 将字符串转成大写或者小写.String toUpperCase();String toLowerCase();7.2 将字符串两端的多个空格去除.String trim();7.3 对两个字符串进行自然顺序的比较int compareTo(string);*/class  StringMethodDemo{public static void method_7(){String s = "   Hello Java   ";sop(s.toUpperCase());sop(s.toLowerCase());sop(s.trim());String s1 = "abc";String s2 = "aaa";sop(s1.compareTo(s2));}public static void method_sub(){String s = "abcdef";sop(s.substring(2));//从指定位置开始到结尾.如果角标不存在,会出现字符串角标越界异常.sop(s.substring(2,4));//包含头,不包含尾.s.substring(0,s.length());}public static void method_split(){String s = "zhangsan,lisi,wangwu";String[] arr = s.split(",");for(int x = 0;x<arr.length;x++){sop(arr[x]);}}public static void method_replace(){String s = "hello java";//String s1 = s.replace('a','v');//如果要替换的字符不存在,返回的还是原串.String s1 = s.replace("java","world");sop("s="+s);sop("s1="+s1);}public static void method_trans(){char[] arr = {'a','b','c','d','e','f'};String s = new String(arr,1,3);sop("s="+s);String s1 = "zhhjsd";char[] chs = s1.toCharArray();for(int x=0; x<chs.length(); x++){sop("ch="+chs[x]);}}public static void methid_is(){String str = "ArrayDemo.java";//判断文件名称是否以Array单词开头.sop(str.startsWith("Array"));//判断文件名称是否是.java的文件sop(str.endsWith(".java"));//判断文件中是否包含Demosop(str.contanins("Demo"));}public static void method_get(){String str = "abcdefd";//长度sop(str.length());//根据索引获取字符sop(str.charAt(5));//当访问到字符串中不存在的角标时会发生StringIndexOutOfBoundsException.//根据字符获取索引sop(str.indexOf('a',3));//如果没有找到,返回-1//反向索引一个字符出现的位置sop(str.lastindexOf('a'));}public static void main(String[] args) {method_7();method_sub();method_trans();method_is();method_get();}public static void sop(Object obj){System.out.println(obj);}}


6.String(字符串练习1)
7.String(字符串练习2)
/*1.模拟一个trim方法,去除字符串两端的空格.思路:1.判断字符串第一个位置是否为空格,如果是继续向下判断,知道不是空格为止,2.当开始和结尾都判断到不是空格时,就是要获取的字符串.2.将一个字符串进行反转.将字符串中指定部分进行反转,"abcdefg";"abcdef"思路: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());}public static void reverse(char[] chs,int x,int y){for(int start=x,end=y-1;start<end;start++,end--){swap(chs,start,end);}}public 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.String(字符串练习3)
/*3.获取一个字符串在另一个字符串中出现的次数."abkkcdkkefkkskk"思路:1.定义一个计数器.2.获取kk第一次出现的位置.3.从第一次出现的位置后剩余的字符串中继续获取kk出现的位置.每获取一次就计数一次.4.当获取不到时,计数完成.*/class  StringTest2{public static void main(String[] args) {String str = "kkabkkcdkkefkks";sop("count==="+getSubCount_2(str,"kk"));}public static void sop(String str){System.out.println(str);}//练习三方式一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;}}



9.String(字符串练习4)
/*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;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 sop(String str){System.out.println(str);}public static void main(String[] args) {String s1 = "abcwerthelloyuiodef";String s2 = "cvhellobnm";sop(getMaxSubString(s2,s1));}}



10.StringBuffer(常见功能-添加)
11.StringBuffer(常见功能-删除和修改)
12.StringBuilder.
/*StringBuffer是字符串缓冲区.是一个容器.特点:1.长度是可变化的.2.可以直接操作多个数据类型.3.最终会通过toString方法变成字符串.C create  U update  R read  D delete1.存储.StringBuffer append():将指定数据作为参数添加到已有数据结尾处.StringBuffer insert(index,数据):可以将数据插入到制定index位置.2.删除.StringBuffer delete(start,end):删除缓冲区中的数据,包含start,不包含end.StringBuffer deleteCharAt(index):删除指定位置的字符.3.获取.char charAt(int index)int indexOf(String str)int lastIndexOf(String str)int length()String substring(int start,int end)4.修改.StringBuffer replace(start,end,string)void setCharAt(int index,char ch);5.反转.StringBuffer reverse();6.将缓冲区中指定数据存储到指定字符数组中.void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin);JDK1.5版本后出现了StringBuilder.StringBuffer是线程同步.StringBuilder是线程不同步.以后开发,建议使用StringBuilder.升级三个因素:1.提高效率.2.简化书写.3.提高安全性.*/class Demo{}class  StringBufferDemo{public static void main(String[] args) {//method_add();//method_del();//method_update();StringBuffer sb = new StringBuffer("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(4,7);draw(3,6);StringBuilder sb1 = new StringBuilder();sb1.append(new Demo()).append(new Demo());sop("sb1="+sb1);}public static void sop(String str){System.out.println(str);}public static void method_update(){StringBuffer sb = new StringBuffer("abcde");sb.replace(1,4,"java");sb.setCharAt(2,'k');sop(sb.toString());}public static void method_del(){StringBuffer sb = new StringBuffer("abcde");sb.delete(1,3);//清空缓冲区sb.delete(0,sb.length());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));//truesb.insert(1,"qq");sop(sb.toString());//abcdtrue34}public static void draw(int row,int col){StringBuffer sb = new StringBuffer();for(int x=0; x<row;x++){for(int y=0;y<col;y++){sb.append("*");}sb.append("\r\n");}sop(sb.toString());}}



13.基本数据类型对象包装类.
/*基本数据类型对象包装类.byte    Byteshort   Shortint     Intlong    Longboolean Booleanfloat   Floatdouble  Doublechar    Character基本数据类型对象包装类的最常见作用.就是用于基本数据类型和字符串类型之间做转换.基本数据类型转成字符串.基本数据类型+""基本数据类型.toString(基本数据类型值);如:Integer.toString(34);//将整数34变成"34".字符串转成基本数据类型.xxx a = Xxx.parseXxx(String);int a = Integer.parseInt("123");double b = Double.parseDouble("12.23");boolean b = Boolean.parseBoolean("true");Integer i = new Integer("123");int num = i.intValue();十进制转成其他进制.toBinaryString();toHexString();toOctalString();其他进制转成十进制parseInt(string,radix);*/class  {public static void main(String[] args) {//整数类型的最大值.sop("int max:"+Integer.MAX_VALUE);//将一个字符串转成整数.int num = Integer.parseInt("123");//必须传入数字格式的字符串.//long x = Long.parseLong("123");sop("num= "+num);sop(Integer.toBinaryString(-6));sop(Integer.toHexString(60));int x = Integer.parseInt("3c",16);sop("x="+x);}}




14.基本数据类型对象包装类新特性.
/*JDK1.5版本以后出现的新特性*/class  IntegerDemo1{public static void main(String[] args) {Integer x = new Integer(4);Integer x = 4;//自动装箱.//new Integer(4).x = x/*x.intValue()*/ + 2//x+2:x进行自动拆箱.变成int类型,和2进行加法运算.//再将和进行装箱赋给xInteger m = 128;Integer n = 128;sop("m==n:"+(m==n));Integer a = 127;Integer b = 127;sop("a==b:"+(a==b));//结果为true.因为a和b指向了同一个Integer对象.//因为当数值在byte范围内,对于新特性,如果该数值已经存在,则不会再开辟新的空间.}public static void method();{Integer x = new Integer("123");Integer y = new Integer(123);sop("x==y:"+(x==y));sop("x.equals(y):"+x.equals(y));}public static void sop(String str){System.out.println(str);}}


---------------------- android培训、java培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net/heima
原创粉丝点击