java学习--String类

来源:互联网 发布:网络模块 编辑:程序博客网 时间:2024/05/17 02:38

01)String(概述)

字符串(String)是由字符构成的一个序列。在Java语言中,字符串是一个对象。String类中有11个构造方法以及40多个处理字符串的方法
[java] view plaincopy
  1. public class StringDemo {  
  2.     public static void main(String[] args) {  
  3.         //字符串的特点:一旦被初始化就不可以改变。  
  4.         String s1 = "Hello world";//s是一个类类型变量,"Hello world"就是一个对象。  
  5.         String s = "Welcome to Java";//"Hello world"在内存中还存在,仅仅只是s这个引用指向了"Welcome to Java"。  
  6.         System.out.println(s);  
  7.         String s2 = new String("Hello world");  
  8.         /* 
  9.          * s1和s2有什么区别? 
  10.          * s1在内存中有一个对象。 
  11.          * s2在内存中有两个对象。 
  12.          */  
  13.         System.out.println(s1 == s2);//显示:false。  
  14.         System.out.println(s1.equals(s2));//显示:true。String类复写了Object类中equals方法。该方法用与判断字符串是否相等。  
  15.     }  
  16. }  


02)常见功能——获取和判断

[java] view plaincopy
  1. /* 
  2.  * String类用于描述字符串事物。 
  3.  * 那么它就提供了多个方法对字符串进行操作。 
  4.  *  
  5.  * 常见的操作有哪些? 
  6.  * "Hello world" 
  7.  * 1:获取。 
  8.  *      1.1:字符串中包含的字符数,也就是字串串的长度。int length():获取长度。 
  9.  *      1.2:根据位置获取位置上的某个字符。char charAt(int index): 
  10.  *      1.3:根据字符获取该字符在字符串的位置。int indexOf(int ch):返回的是ch在字符串中第一次出现的位置。indexOf(int ch, int fromIndex):返回在此字符串中第一次出现指定字符处的位置。 
  11.  * 2:判断。 
  12.  *      2.1:字符串中是否包含某一个字串。 
  13.  *      2.2:字符串中是否有内容。boolean isEmpty() 
  14.  *      2.3:字符串是否是以指定内容开头。boolean startsWith(str) 
  15.  *      2.4:字符串是否是以指定内容结尾。boolean endsWith(str) 
  16.  *      2.5:判断字符串内容是否相同。 
  17.  *      2.6:判断内容是否相同,并忽略大小写。 
  18.  */  
  19. public class StringMethodDemo {  
  20.     public static void main(String[] args) {  
  21.         method_get();  
  22.         method_is();  
  23.     }  
  24.     public static void method_get(){  
  25.         String s = "Hello world";  
  26.         sop(s.length());//获取长度。  
  27.         sop(s.charAt(7));//获取下标为5的字符。注意:能发生字符串下标越界异常。  
  28.         sop(s.indexOf('o'));  
  29.         sop(s.indexOf('l'3));//如果没有找到,返回-1。  
  30.     }  
  31.     public static void method_is(){  
  32.         String s = "StringMethodDemo.java";  
  33.         sop(s.startsWith("Str"));  
  34.         sop(s.endsWith(".java"));  
  35.         sop(s.contains("Method"));  
  36.     }  
  37.     public static void sop(Object obj){  
  38.         System.out.println(obj);  
  39.     }  
  40. }  

03)转换

[java] view plaincopy
  1. /* 
  2.  * 3:转换 
  3.  *      3.1:将字符数组转成字符串。 
  4.  *              构造函数:String(Char[]) 
  5.  *                      String(Char[], offset, count) 
  6.  *              静态方法:static String copyValueOf(char[]) 
  7.  *                      static String copyValueOf(char[], offset, count) 
  8.  *      3.2:将字符串转成字符数组。 
  9.  *              char[] toCharArray() 
  10.  *      3.3:将字节数组转成字符串。 
  11.  *      3.4:将字符串转成字节数组。 
  12.  *              byte[] getBytes() 
  13.  *      3.5:将基本数据类型转换成字符串。 
  14.  *              static String valueOf(int) 
  15.  *              static String valueOf(double) 
  16.  *   
  17.  *          特殊:字符串和字节数组在转换过程中,是可以指定编码表的。 
  18.  */  
  19. public class StringMethodDemo_2 {  
  20.     public static void main(String[] args) {  
  21.         method_trance();  
  22.     }  
  23.     public static void method_trance(){  
  24.         char[] arr = {'a''b''c''d''e'};  
  25.         String s1 = new String(arr);  
  26.         String s2 = new String(arr, 13);  
  27.         sop("s1: " + s1);  
  28.         sop("s2: " + s2);  
  29.         String s3 = "Hello world";  
  30.         char[] chs3 = s3.toCharArray();  
  31.         for (int i = 0; i <chs3.length; i++){  
  32.             sop("chs3: " + chs3[i]);  
  33.         }  
  34.     }  
  35.     public static void sop(Object obj){  
  36.         System.out.println(obj);  
  37.     }  
  38. }  


04)切割和替换
[java] view plaincopy
  1. /* 
  2.  * 4:替换 
  3.  *      String replace(char oldChar, char newChar)  
  4.  * 5:切割 
  5.  *      String[] split(String regex) 注意:如果字符串不匹配,将返回原来字符串。 
  6.  * 6:子串 
  7.  *      String substring(int beginIndex)  注意:如果下标不存在,会发生字符串下标越界异常。 
  8.  *      String substring(int beginIndex, int endIndex)  
  9.  */  
  10. public class StringMethodDemo_3 {  
  11.     public static void main(String[] args) {  
  12.         method_replace();//替换  
  13.         method_split();//切割  
  14.         method_sup();//子串  
  15.     }  
  16.     public static void method_replace(){//替换  
  17.         String s = "Welcome to Java";  
  18.         String s1 = s.replace('o''t');//将字符o替换成t  
  19.         String s2 = s.replace("to""hehe");//将字符串to替换成hehe  
  20.         sop("s: " + s);//字符串一旦被初始化,s就不会被改变。  
  21.         sop("s1: " + s1);  
  22.         sop("s2: " + s2);  
  23.     }  
  24.     public static void method_split(){//切割  
  25.         String s = "hah, heh, heihei";  
  26.         String[] arr = s.split(", ");//如果不匹配就返回原值。  
  27.         for (int i = 0; i < arr.length; i++){  
  28.             sop(arr[i]);  
  29.         }  
  30.     }  
  31.     public static void method_sup(){//子串  
  32.         String s = "abcdefg";  
  33.         String s1 = s.substring(3);//从头到尾。//如果下标不存在,会发生字符串下标越界异常。  
  34.         String s2 = s.substring(35);//包含头,不包含尾。  
  35.         sop("s: " + s);  
  36.         sop("s1: " + s1);  
  37.         sop("s2: " + s2);  
  38.     }  
  39.     public static void sop(Object obj){  
  40.         System.out.println(obj);  
  41.     }  
  42. }  

05)比较和去空格

[java] view plaincopy
  1. /* 
  2.  * 7:转换,去空格,比较 
  3.  *      7.1:将字符串转换成大写或则小写。 
  4.  *          String toLowerCase() //转换成小写 
  5.  *           String toUpperCase() //转换成大写 
  6.  *      7.2:将字符串两端的空格去掉。 
  7.  *          String trim()  
  8.  *      7.3:对两个字符串进行自然顺序的比较。 
  9.  *          int compareTo(String anotherString)  
  10.  */  
  11. public class StringMethodDemo_4 {  
  12.     public static void main(String[] args) {  
  13.         method_4();  
  14.     }  
  15.       
  16.     public static void method_4(){//7:转换,去空格,比较  
  17.         String s = "   Welcome to Java    ";  
  18.         sop(s.toLowerCase());//转换成小写  
  19.         sop(s.toUpperCase());//转换成大写  
  20.         sop(s.trim());//去两端空格  
  21.           
  22.         String s1 = "abc";  
  23.         String s2 = "aaa";  
  24.         sop(s1.compareTo(s2));  
  25.     }  
  26.     public static void sop(Object obj){  
  27.         System.out.println(obj);  
  28.     }  
  29. }  

06)字符串练习(1)——去两端空格


[java] view plaincopy
  1. public class StringTest_1 {//去两端空格  
  2.     public static void sop(Object obj){  
  3.         System.out.println(obj);  
  4.     }  
  5.     public static void main(String[] args) {  
  6.         String s = "      ab,    ac,     ad    ";  
  7.         sop("(" + s + ")");//打印去空格前的字符串。  
  8.         sop("(" + myTrim(s) + ")");//去空格后。  
  9.     }  
  10.     //练习一,去除字符串两端空格。  
  11.     public static String myTrim(String str){  
  12.         int start = 0;  
  13.         int end = str.length() - 1;  
  14.         while(start <= end && str.charAt(start) == ' ')  
  15.             start++;  
  16.         while(start <= end && str.charAt(end) == ' ')  
  17.             end--;  
  18.         return str.substring(start, end + 1);  
  19.     }  
  20. }  


06)字符串练习(二)——将一个字符串进行反转

[java] view plaincopy
  1. /* 
  2.  * 练习二,将字符串进行反正。 
  3.  * 思路: 
  4.  * 1,将字符串变成数组。 
  5.  * 2,将数组进行反转。 
  6.  * 3,将数组变成字符串。 
  7.  */  
  8. public class StringTest_2 {  
  9.     static Reverse_2 r = new Reverse_2();  
  10.     public static void sop(Object obj){  
  11.         System.out.println(obj);  
  12.     }  
  13.     public static void main(String[] args) {  
  14.         String s1 = "   abc   abc   ";  
  15.         String s2 = "   abc   abc   ";  
  16.         sop("(" + s1 + ")");  
  17.         System.out.println("------------------");  
  18.         sop("(" + reverseString(s1) + ")");//反转全部字符  
  19.         System.out.println("------------------");  
  20.         sop("(" + reverseString(s2) + ")");//反正指定位置字符  
  21.     }  
  22.     //练习二(1),将字符串进行反正。  
  23.     public static String reverseString(String s){//练习二(1)  
  24.         return r.reverseString(s, 0, s.length());  
  25.     }  
  26.     private static void reverse(char[] chs){//练习二(1)  
  27.         for (int start = 0, end = chs.length - 1; start < end; start++, end--){  
  28.             swap(chs, start, end);  
  29.         }  
  30.     }  
  31.     static void swap(char[] chs, int start, int end){//置换位置  
  32.         char temp = chs[start];  
  33.         chs[start] = chs[end];  
  34.         chs[end] = temp;  
  35.     }  
  36. }  
  37. class Reverse_2{  
  38.     //练习二(2),反转字符串中指定字符  
  39.     public static String reverseString(String s, int start, int end){//练习二(2)  
  40.         char[] chs = s.toCharArray();//1,将字符串变成数组。  
  41.         reverse(chs, start, end);//2,将数组中指定部分反转。  
  42.         return new String(chs);//3,将数组变成字符串。  
  43.     }  
  44.     private static void reverse(char[] chs, int a, int b){//练习二(2)  
  45.         for (int start = a, end = b - 1; start < end; start++, end--){  
  46.             StringTest_2.swap(chs, start, end);  
  47.         }  
  48.     }  
  49. }  
运行结果如下图所示:


07)字符串练习(三)——获取一个字符串在另一个字符串出现的次数


[java] view plaincopy
  1. public class StringTest_3 {  
  2.     public static void sop(Object obj){  
  3.         System.out.println(obj);  
  4.     }  
  5.     public static void main(String[] args) {  
  6.         String str = "hesafsheehesehesehesd";  
  7. //      sop("count = " + getSubCount(str, "he"));  
  8.         sop("count = " + getSubCount_2(str, "he"));  
  9.     }  
  10.     public static int getSubCount(String str, String key){//第一种方式  
  11.         int count = 0;  
  12.         int index = 0;  
  13.         while((index = str.indexOf(key)) != -1){  
  14.             sop("str = " + str);  
  15.             str = str.substring(index + key.length());//返回新字符串,从索引开始。  
  16.             count++;  
  17.         }  
  18.         return count;  
  19.     }  
  20.     public static int getSubCount_2(String str, String key){//第二种方式  
  21.         int count = 0;  
  22.         int index = 0;  
  23.         while((index = str.indexOf(key, index)) != -1){  
  24.             sop("index = " + index);  
  25.             index = index + key.length();//索引下标值加key长度。  
  26.             count++;  
  27.         }  
  28.         return count;  
  29.     }  
  30. }  

07)字符串练习(四)——获取两个字符串中最大相同子串。


[java] view plaincopy
  1. public class StringTest_4 {  
  2.     public static void sop(Object obj){  
  3.         System.out.println(obj);  
  4.     }  
  5.     public static void main(String[] args) {  
  6.         String s1 = "afhasdlkfhelfslohafasfadfa";  
  7.         String s2 = "affhelfsskd";  
  8.         sop(getMaxSubString(s1, s2));  
  9.     }  
  10.     public static String getMaxSubString(String s1, String s2){  
  11.         String max = "", min = "";  
  12.         max = (s1.length() > s2.length()) ? s1 : s2;//获取最长字符串,未知。  
  13.         min = (max == s1) ? s2 : s1;//如果最长字符串是s1,那么s2是最短字符串,否则s1是最短的。  
  14.         for (int i = 0; i < min.length(); i++){  
  15.             for (int j = i, k = min.length() - i; k != min.length() + 1; j++, k++){  
  16.                 String temp = min.substring(j, k);//获取从下标j到(k-1)的字符串。  
  17.                 if(s1.contains(temp))//如果最长字符串中包含字符串(temp)  
  18.                     return temp;//那么返回temp。  
  19.             }  
  20.         }  
  21.         return "";  
  22.     }  
  23. }  

10)StringBuffer(常见功能——添加、删除和修改)

[java] view plaincopy
  1. /* 
  2.  * StringBuffer是字符串缓冲区。 
  3.  * 是一个容器。 
  4.  * 特点: 
  5.  * 1:长度是可变化的。 
  6.  * 2:可以直接操作多个数据类型。 
  7.  * 3:最终会通过toString()方法变成字符串。 
  8.  * 【C:create U:updete R:read D:delete】 
  9.  * 1:存储。 
  10.  *      StringBuffer append():将指定数据作为参数添加到已有数据结尾处。 
  11.  *      StringBuffer insert(index, 数据):将数据插入到指定index位置。 
  12.  * 2:删除。 
  13.  *      StringBuffer delete(start, end):删除缓冲区中的数据,包含start,不包含end。 
  14.  *      StringBuffer delete(index):删除指定位置的字符。 
  15.  * 3:获取。 
  16.  *      char charAt(int index): 
  17.  *      int indexOf(Strubg str): 
  18.  *      int lastIndex(String str): 
  19.  *      int length(): 
  20.  *      String subString(int start, int end): 
  21.  * 4:修改。 
  22.  *      StringBuffer replace(int start, int end, String str): 
  23.  *      void setCharAt(int index, char ch): 
  24.  * 5:反转 
  25.  *      StringButffer reverse(): 
  26.  */  
  27. public class StringBufferDemo {  
  28.     public static void sop(String str){  
  29.         System.out.println(str);  
  30.     }  
  31.     public static void main(String[] args) {  
  32.         System.out.println("----------method_add----------");  
  33.         method_add();  
  34.         System.out.println("----------method_del----------");  
  35.         method_del();  
  36.         System.out.println("----------method_update----------");  
  37.         method_update();  
  38.     }  
  39.     public static void method_add(){//添加  
  40.         StringBuffer sb = new StringBuffer();  
  41.         sb.append("haha ").append(true).append(" " + 12345);//方法调用链。  
  42.         sb.insert(9" hiahia ");//添加  
  43.         sop(sb.toString());  
  44.     }  
  45.     public static void method_del(){//删除  
  46.         StringBuffer sb = new StringBuffer("StringBufferDemo");  
  47.         sop(sb.toString());//删除前  
  48.         System.out.println("---------------");  
  49.         sb.delete(68);//删除下标6到(8-1)的字符。  
  50.         sop(sb.toString());//删除后  
  51.         System.out.println("---------------");  
  52. //      sb.delete(0, 1);  
  53.         sb.deleteCharAt(0);//删除下标为0的字符。  
  54.         sop(sb.toString());  
  55.         sb.delete(0, sb.length());//清空缓冲区。  
  56.         sop(sb.toString());  
  57.         System.out.println("---------------");  
  58.     }  
  59.     public static void method_update(){  
  60.         StringBuffer sb = new StringBuffer("StringBufferDemo");  
  61.         sop(sb.replace(36"java").toString());//返回StrjavaBufferDemo。  
  62.         sb.setCharAt(3'J');  
  63.         sop(sb.toString());//返回StrJavaBufferDemo。  
  64.     }  
  65. }  


11)StringBuilder
一个可变的字符序列。该类被设计用作StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer 要快。
[java] view plaincopy
  1. /* 
  2.  * JDK1.5之后出现StringBuilder。 
  3.  * StringBuffer:线程是同步的。 
  4.  * StringBuilder:线程不同步。 
  5.  * 将 StringBuilder 的实例用于多个线程是不安全的。如果需要这样的同步,则建议使用 StringBuffer。 
  6.  * 升级三个因数: 
  7.  * 1:提高效率 
  8.  * 2:简化书写 
  9.  * 3:提高安全性 
  10.  */  

12)基本数据类型对象包装类
[java] view plaincopy
  1. /* 
  2.  * 基本数据类型对象包装类。 
  3.  * byte     Byte 
  4.  * short    Short 
  5.  * int      Integer 
  6.  * long     Long 
  7.  * boolean  Boolean 
  8.  * float    Float 
  9.  * double   Double 
  10.  * char     Character 
  11.  *  
  12.  * 最常见作用:用于基本数据类型和字符串类型之间做转换。 
  13.  * 基本数据类型转字符串类型:(基本数据类型 + "")(基本数据类型.toString(基本数据类型值)) 
  14.  * 字符串类型转基本数据类型:数据类型 变量 = 基本数据类型包装类.parse数据类型(""): 
  15.  *  
  16.  * 十进制转成其它进制:toBinaryString()、toHexString()、toOctalString() 
  17.  * 其它进制转成十进制:parseInt(String s, int index) 
  18.  */  
  19. public class IntegerDemo {  
  20.     public static void sop(String str){  
  21.         System.out.println(str);  
  22.     }  
  23.     public static void main(String[] args) {  
  24.         //整数类型的最大值。  
  25.         sop("Int max = " + Integer.MAX_VALUE);  
  26.         System.out.println("---------------------");  
  27.         //将一个整数转成字符串。  
  28.         String num1 = Integer.toString(20);  
  29.         System.out.println("num1 = " + num1);  
  30.         sop("num1 = " + (num1 + 1));  
  31.         System.out.println("---------------------");  
  32.         //将一个字符串转成一个整数。  
  33.         int num2 = Integer.parseInt("20");//必须输入数字格式的字符串。  
  34.         sop("num2 = " + (num2 + 2));  
  35.         System.out.println("---------------------");  
  36.         //  
  37.         int a = Integer.parseInt("10101010"2);  
  38.         int b = Integer.parseInt("3c"16);  
  39.         sop("a = " + a);  
  40.         sop("b = " + b);  
  41.         System.out.println("---------------------");  
  42.     }  
  43. }  


14)新特性
[java] view plaincopy
  1. public class IntegerDemo_2 {  
  2.     public static void sop(String str){  
  3.         System.out.println(str);  
  4.         System.out.println("------------------");  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         method_1();  
  8.         method_2();  
  9.     }  
  10.     public static void method_1(){  
  11.         Integer a = new Integer("123");  
  12.         Integer b = new Integer(123);  
  13.         sop("a==b? " + (a == b));  
  14.         sop("a.equals(b)? " + (a.equals(b)));  
  15.   
  16.     }  
  17.     public static void method_2(){  
  18.         Integer c = 110;//自动装箱。 110等于Integer(10)。  
  19.         sop("c = " + c);  
  20.         c = c + 1;//先自动拆箱c(c.intValue()),与1向加后,在将值自动装箱。  
  21.         sop("c = " + c);  
  22.         Integer d = 128;//byte数据类型的零界点。  
  23.         Integer e = 128;  
  24.         sop("d==e? " + (d == e));  
  25.         Integer f = 120;  
  26.         Integer g = 120;  
  27.         sop("f==g? " + (f == g));//f和g指向同一个对象。  
  28.     }  
  29. }  

0 0