String类_获取,判断,转换,替换,切割

6.1 Sting类

 

String类适用于描述字符串事物。

那么它就提供了多个方法对字符串进行操作。

 

常见的操作有哪些?

"abcd"

 

6.1.1.获取。

         1.1 字符串中的包含的字符数,也就是字符串的长度。

                   intlength():获取长度。

         1.2 根据位置获取位置上某个字符。

                   charcharAt(int index):

         1.3 根据字符获取该字符在字符串中位置。

                   intindexOf(int ch):返回的是ch在字符串中第一次出现的位置。

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

 

                   intindexOf(String str):返回的是str在字符串中第一次出现的位置。

                   intindexOf(String str, int fromIndex) :从fromIndex指定位置开始,获取str在字符串中出现的位置。

 

                   intlastIndexOf(int ch) :

 

                  

6.1.2.判断。

         2.1 字符串中是否包含某一个子串

                   booleancontains(str):

                   特殊之处:indexOf(str):可以索引str第一次出现位置,如果返回-1.表示该str不在字符串中存在。

                    所以,也可以用于对指定判断是否包含。

                   if(str.indexOf("aa")!=-1)

 

                   而且该方法即可以判断,有可以获取出现的位置。

 

         2.2 字符中是否有内容。

                   booleanisEmpty(): 原理就是判断长度是否为0.

         2.3 字符串是否是以指定内容开头。

                   booleanstartsWith(str);

         2.4 字符串是否是以指定内容结尾。

                   booleanendsWith(str);

         2.5 判断字符串内容是否相同。复写了Object类中的equals方法。

                   booleanequals(str);

         2.6 判断内容是否相同,并忽略大小写。

                   booleanequalsIgnoreCase();

        

6.1.3.转换。

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

                   构造函数:String(char[])

                                       String(char[],offset,count):将字符数组中的一部分转成字符串。

 

                   静态方法:

                                     staticString copyValueOf(char[]);

                                     staticString copyValueOf(char[] data, int offset, int count)

 

                                     staticString valueOf(char[]):

 

                  

         3.2 将字符串转成字符数组。**

                   char[]toCharArray():

 

         3.3 将字节数组转成字符串。

                            String(byte[])

                            String(byte[],offset,count):将字节数组中的一部分转成字符串。

 

         3.4 将字符串转成字节数组。

                            byte[]  getBytes():

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

                   staticString valueOf(int)

                   staticString valueOf(double)

 

                   //3+"";//String.valueOf(3);

 

                   特殊:字符串和字节数组在转换过程中,是可以指定编码表的。

 

6.1.4.替换

         Stringreplace(oldchar,newchar);

 

6.1.5.切割

         String[]split(regex);

 

6.1.6.子串。获取字符串中的一部分

         Stringsubstring(begin);

         Stringsubstring(begin,end);

 

6.1.7.转换,去除空格,比较

         7.1将字符串转成大写或则小写。

                    String toUpperCase();

                    String toLowerCase();

 

         7.2 将字符串两端的多个空格去除

                   Stringtrim();

 

         7.3 对两个字符串进行自然顺序的比较

                   intcompareTo(string);

 

练习一:String类常见操作

 

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class StringMethodDemo  
  2. {  
  3.    
  4.          public static void method_7()  
  5.          {  
  6.                    String s = "    Hello Java     ";  
  7.                    sop(s.toLowerCase());  
  8.                    sop(s.toUpperCase());  
  9.                    sop(s.trim());  
  10.    
  11.                    String s1 = "a1c";  
  12.                    String s2 = "aaa";  
  13.    
  14.                    sop(s1.compareTo(s2));  
  15.          }  
  16.          public static void method_sub()  
  17.          {  
  18.                    String s = "abcdef";  
  19.    
  20.                    sop(s.substring(2));//从指定位置开始到结尾。如果角标不存在,会出现字符串角标越界异常。  
  21.                    sop(s.substring(2,4));//包含头,不包含尾。s.substring(0,s.length());  
  22.          }  
  23.    
  24.          public static void  method_split()  
  25.          {  
  26.                    String s = "zhagnsa,lisi,wangwu";  
  27.    
  28.                    String[] arr  = s.split(",");  
  29.    
  30.                    for(intx = 0; x<arr.length; x++)  
  31.                    {  
  32.                             sop(arr[x]);  
  33.                    }  
  34.          }  
  35.    
  36.          public static void method_replace()  
  37.          {  
  38.                    String s = "hello java";  
  39.    
  40.                    //String s1 = s.replace('q','n');//如果要替换的字符不存在,返回的还是原串。  
  41.    
  42.    
  43.                    String s1 = s.replace("java","world");  
  44.                    sop("s="+s);  
  45.                    sop("s1="+s1);  
  46.          }  
  47.    
  48.          public static void method_trans()  
  49.          {  
  50.                    char[] arr = {'a','b','c','d','e','f'};  
  51.    
  52.                    String s= new String(arr,1,3);  
  53.    
  54.                    sop("s="+s);  
  55.    
  56.                    String s1 = "zxcvbnm";  
  57.    
  58.                    char[] chs = s1.toCharArray();  
  59.    
  60.                    for(intx=0; x<chs.length; x++)  
  61.                    {  
  62.                             sop("ch="+chs[x]);  
  63.                    }  
  64.          }  
  65.          public static void method_is()  
  66.          {  
  67.                    String str = "ArrayDemo.java";  
  68.                     
  69.                    //判断文件名称是否是Array单词开头。  
  70.                    sop(str.startsWith("Array"));  
  71.                    //判断文件名称是否是.java的文件。  
  72.                    sop(str.endsWith(".java"));  
  73.                    //判断文件中是否包含Demo  
  74.                    sop(str.contains(".java"));  
  75.    
  76.          }  
  77.    
  78.    
  79.          public static void method_get()  
  80.          {  
  81.                    String str = "abcdeakpf";  
  82.    
  83.                    //长度  
  84.                   sop(str.length());  
  85.    
  86.                    //根据索引获取字符。  
  87.                    sop(str.charAt(4));  
  88. //当访问到字符串中不存在的角标时会发生StringIndexOutOfBoundsException。  
  89.    
  90.                    //根据字符获取索引  
  91.                    sop(str.indexOf('m',3));//如果没有找到,返回-1.  
  92.                     
  93.                    //反向索引一个字符出现位置。  
  94.                    sop(str.lastIndexOf("a"));  
  95.                     
  96.          }  
  97.          public static void main(String[] args)  
  98.          {  
  99.                    method_7();  
  100. //               method_trans();  
  101. //               method_is();  
  102. //               method_get();  
  103.                    /* 
  104.                    String s1 = "abc"; 
  105.                    String s2 = new String("abc"); 
  106.   
  107.                    String s3 = "abc"; 
  108.                    System.out.println(s1==s2); 
  109.                    System.out.println(s1==s3); 
  110.   
  111.                    */  
  112.          }  
  113.    
  114.          public static void sop(Object obj)  
  115.          {  
  116.                    System.out.println(obj);  
  117.          }  
  118. }  


 

练习二:灵活运用String的常见操作

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* 
  2. 1,模拟一个trim方法,去除字符串两端的空格。 
  3.          思路: 
  4.          1,判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止。 
  5.                    结尾处判断空格也是如此。 
  6.          2,当开始和结尾都判断到不是空格时,就是要获取的字符串。 
  7.   
  8.   
  9.   
  10. 2,将一个字符串进行反转。将字符串中指定部分进行反转,"abcdefg";abfedcg 
  11.          思路: 
  12.          1,曾经学习过对数组的元素进行反转。 
  13.          2,将字符串变成数组,对数组反转。 
  14.          3,将反转后的数组变成字符串。 
  15.          4,只要将或反转的部分的开始和结束位置作为参数传递即可。 
  16.   
  17.   
  18. */  
  19.    
  20. class StringTest  
  21. {  
  22.    
  23.          public static void sop(String str)  
  24.          {  
  25.                    System.out.println(str);  
  26.          }  
  27.          public static void main(String[] args)  
  28.          {  
  29.                    String s = "      ab cd      ";  
  30.    
  31.                    sop("("+s+")");  
  32. //               s= myTrim(s);  
  33. //               sop("("+s+")");  
  34.    
  35.                    sop("("+reverseString(s)+")");  
  36.                     
  37.          }  
  38.    
  39.    
  40.          //将字符串反转。  
  41.          /* 
  42.          思路: 
  43.          1,将字符串变成数组。 
  44.          2,对数组反转。 
  45.          3,将数组变成字符串。 
  46.          */  
  47.    
  48.          public static String reverseString(String s,int start,int end)  
  49.          {  
  50.                    //字符串变数组。  
  51.                    char[] chs = s.toCharArray();  
  52.    
  53.                    //反转数组。  
  54.                    reverse(chs,start,end);  
  55.    
  56.                    //将数组变成字符串。  
  57.                    return new String(chs);  
  58.          }  
  59.          public static String reverseString(String s)  
  60.          {  
  61.                    return reverseString(s,0,s.length());  
  62.                     
  63.          }  
  64.    
  65.          private static void reverse(char[] arr,int x,int y)  
  66.          {  
  67.                    for(int start=x,end=y-1; start<end ; start++,end--)  
  68.                    {  
  69.                             swap(arr,start,end);  
  70.                    }  
  71.          }  
  72.          private static void swap(char[] arr,int x,int y)  
  73.          {  
  74.                    char temp = arr[x];  
  75.                    arr[x]= arr[y];  
  76.                    arr[y]= temp;  
  77.          }  
  78.    
  79.          //去除字符串两端空格。  
  80.          public static String myTrim(String str)  
  81.          {  
  82.                    int start = 0,end = str.length()-1;  
  83.    
  84.                    while(start<=end&& str.charAt(start)==' ')  
  85.                             start++;  
  86.    
  87.                    while(start<=end&& str.charAt(end)==' ')  
  88.                             end--;  
  89.    
  90.                    return str.substring(start,end+1);  
  91.          }  
  92. }  


练习三:获取一个字符串在另一个字符串中出现的次数

 

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* 
  2. 3,获取一个字符串在另一个字符串中出现的次数。 
  3.          "abkkcdkkefkkskk" 
  4.   
  5.          思路: 
  6.          1,定义个计数器。 
  7.          2,获取kk第一次出现的位置。 
  8.          3,从第一次出现位置后剩余的字符串中继续获取kk出现的位置。 
  9.                    每获取一次就计数一次。 
  10.          4,当获取不到时,计数完成。 
  11. */  
  12.    
  13. class StringTest2  
  14. {         
  15.          /* 
  16.          方法一 
  17.          */  
  18.    
  19.          public static int getSubCount(String str,String key)  
  20.          {  
  21.                    int count = 0;  
  22.                    int index = 0;  
  23.    
  24.                    while((index=str.indexOf(key))!=-1)  
  25.                    {  
  26.                             sop("str="+str);  
  27.                             str= str.substring(index+key.length());  
  28.    
  29.                             count++;   
  30.                    }  
  31.                    return count;  
  32.          }  
  33.    
  34.          /* 
  35.          方法二 
  36.          */  
  37.          public static int getSubCount_2(String str,String key)  
  38.          {  
  39.                    int count = 0;  
  40.                    int index = 0;  
  41.    
  42.                    while((index=str.indexOf(key,index))!=-1)  
  43.                    {  
  44.                             sop("index="+index);  
  45.                             index= index + key.length();  
  46.    
  47.                             count++;  
  48.                    }  
  49.                    return count;  
  50.          }  
  51.    
  52.          public static void main(String[] args)  
  53.          {  
  54.                    String str = "kkabkkcdkkefkks";  
  55.    
  56.                    ///sop("count====="+str.split("kk").length);split()不建议使用。  
  57.    
  58.                    sop("count="+getSubCount_2(str,"kk"));  
  59.          }  
  60.    
  61.          public static void sop(String str)  
  62.          {  
  63.                    System.out.println(str);  
  64.          }  
  65. }  


 

练习四:获取两个字符串中最大相同子串。

 

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* 
  2. 4.获取两个字符串中最大相同子串。第一个动作:将短的那个串进行长度一次递减的子串打印。 
  3.          "abcwerthelloyuiodef" 
  4.          "cvhellobnm" 
  5.          思路: 
  6.                    1,将短的那个子串按照长度递减的方式获取到。 
  7.                    2,将每获取到的子串去长串中判断是否包含, 
  8.                             如果包含,已经找到!。 
  9. */  
  10. class StringTest3  
  11. {  
  12.          public static String getMaxSubString(String s1,String s2)  
  13.          {   
  14.    
  15.                    String max = "",min = "";  
  16.    
  17.                    max= (s1.length()>s2.length())?s1: s2;  
  18.    
  19.                    min= (max==s1)?s2: s1;  
  20.                     
  21. //               sop("max="+max+"...min="+min);  
  22.                    for(int x=0; x<min.length(); x++)  
  23.                    {  
  24.                             for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++)  
  25.                             {  
  26.                                      String temp = min.substring(y,z);  
  27.                                       
  28.                                      sop(temp);  
  29.                                      if(max.contains(temp))//if(s1.indexOf(temp)!=-1)  
  30.                                                return temp;  
  31.                             }  
  32.                    }  
  33.                    return "";  
  34.          }  
  35.    
  36.    
  37.          public static void main(String[] args)  
  38.          {  
  39.                    String s1 = "ab";  
  40.                    String s2 = "cvhellobnm";  
  41.                    sop(getMaxSubString(s2,s1));  
  42.          }  
  43.    
  44.          public static void sop(String str)  
  45.          {  
  46.                    System.out.println(str);  
  47.          }  
  48. }  


 

6.1.8  StringBuffer是字符串缓冲区

 

StringBuffer是一个容器。

特点:

1,长度是可变化的。

2,可以字节操作多个数据类型。

3,最终会通过toString方法变成字符串。

 

C create U update R read D delete

 

1,存储。

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

         StringBufferinsert(index,数据):可以将数据插入到指定index位置。

 

2,删除。

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

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

        

3,获取。

         charcharAt(int index)

         intindexOf(String str)

         intlastIndexOf(String str)

         intlength()

         Stringsubstring(int start, int end)

 

4,修改。

         StringBufferreplace(start,end,string);

         voidsetCharAt(int index, char ch) ;

 

 

5,反转。

         StringBufferreverse();

 

6,

         将缓冲区中指定数据存储到指定字符数组中。

         voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

 

        

JDK1.5 版本之后出现了StringBuilder.

 

StringBuffer是线程同步。

StringBuilder是线程不同步。

 

以后开发,建议使用StringBuilder

 

升级三个因素:

1,提高效率。

2,简化书写。

3,提高安全性。

 

练习五:StringBuffer操作的练习

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class Demo  
  2. {  
  3. }  
  4.    
  5. class StringBufferDemo  
  6. {  
  7.          public static void main(String[] args)  
  8.          {  
  9.                    //method_update();  
  10.    
  11.                    StringBuilder sb = new StringBuilder("abcdef");  
  12.           
  13.                    char[] chs = new char[6];  
  14.    
  15.                    sb.getChars(1,4,chs,1);//将  
  16.    
  17.                    for(int x=0; x<chs.length; x++)  
  18.                    {  
  19.                             sop("chs["+x+"]="+chs[x]+";");  
  20.                    }  
  21.    
  22.                    draw(3,6);  
  23.                    draw(8,9);  
  24.    
  25. //               StringBuilder sb1 = new StringBuilder();  
  26. //               sb1.append(newDemo()).append(new Demo());  
  27. //               sop("sb1="+sb1);  
  28.          }  
  29.          public static void method_update()  
  30.          {  
  31.                    StringBuffer sb  = newStringBuffer("abcde");  
  32.    
  33. //               sb.replace(1,4,"java");  
  34.                    sb.setCharAt(2,'k');  
  35.    
  36.                    sop(sb.toString());  
  37.           
  38.          }  
  39.          public static void method_del()  
  40.          {  
  41.                    StringBuffer sb  = newStringBuffer("abcde");  
  42.                    
  43. //               sb.delete(1,3);  
  44.                    //清空缓冲区。  
  45.                    //sb.delete(0,sb.length());  
  46.    
  47.                    //sb.delete(2,3);  
  48.                    sb.deleteCharAt(2);  
  49.    
  50.                    sop(sb.toString());  
  51.          }  
  52.    
  53.          public static void method_add()  
  54.          {  
  55.                    StringBuffer sb = new StringBuffer();  
  56.    
  57.                    //sb.append("abc").append(true).append(34);  
  58. //               StringBuffer sb1 = sb.append(34);  
  59. //               sop("sb==sb1:"+(sb==sb1));  
  60.    
  61.                    sb.insert(1,"qq");  
  62.                    sop(sb.toString());//abctrue34  
  63.                    //sop(sb1.toString());  
  64.    
  65.                     
  66.          }  
  67.    
  68.           
  69.          public static void sop(String str)  
  70.          {  
  71.                    System.out.println(str);  
  72.          }  
  73.           
  74.          public static void draw(int row,int col)  
  75.          {  
  76.                    StringBuilder sb = new StringBuilder();  
  77.                    for(int x=0; x<row; x++)  
  78.                    {  
  79.                             for(int y=0; y<col; y++)  
  80.                             {  
  81.                                      sb.append("*");  
  82.                             }  
  83.                             sb.append("\r\n");  
  84.                    }  
  85.    
  86.                    sop(sb.toString());  
  87.          }  
  88.    
  89. }  


 

6.1.9基本数据类型对象包装类。

 

byte Byte

short         short

int              Integer

long          Long

boolean   Boolean

float           Float

double      Double

char          Character

 

 

 

基本数据类型对象包装类的最常见作用,

就是用于基本数据类型和字符串类型之间做转换

 

基本数据类型转成字符串

 

         基本数据类型+""

 

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

 

         如:Integer.toString(34);//将34整数变成"34";

 

 

字符串转成基本数据类型

 

         xxxa = Xxx.parseXxx(String);

 

         inta = Integer.parseInt("123");

 

         doubleb = Double.parseDouble("12.23");

 

         booleanb = Boolean.parseBoolean("true");

 

         Integeri = new Integer("123");

 

         intnum = i.intValue();

 

十进制转成其他进制。

         toBinaryString();

         toHexString();

         toOctalString();

 

 

其他进制转成十进制。

         parseInt(string,radix);

 

练习六:基本数据类型操作

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class IntegerDemo  
  2. {  
  3.          public static void sop(String str)  
  4.          {  
  5.                    System.out.println(str);  
  6.          }  
  7.           
  8.          public static void main(String[] args)  
  9.          {  
  10.                    //整数类型的最大值。  
  11.                    //判断数据是否超出最大值  
  12.                    //sop("intmax :"+Integer.MAX_VALUE);  
  13.    
  14. //               将一个字符串转成整数。  
  15.    
  16.                    int num = Integer.parseInt("123");//必须传入数字格式的字符串。  
  17.                    //long x = Long.parseLong("123");  
  18.    
  19. //               sop("num="+(num+4));  
  20.    
  21. //               sop(Integer.toBinaryString(-6));  
  22. //               sop(Integer.toHexString(60));  
  23.    
  24.                    int x = Integer.parseInt("3c",16);  
  25.    
  26.                    sop("x="+x);  
  27.    
  28.    
  29.          }  
  30. }  


 

6.1.10JDK1.5版本以后出现的新特性,基本数据类型自动装箱、拆箱

 

练习六:基本数据类型的自动拆箱,装箱

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class IntegerDemo1  
  2. {  
  3.          public static void main(String[] args)  
  4.          {  
  5.                     
  6. //               Integer x = new Integer(4);  
  7.    
  8.                    Integer x = 4;//自动装箱。//new Integer(4)  
  9.    
  10.                    x= x + 2;//x+2:x 进行自动拆箱。变成成了int类型。和2进行加法运算。  
  11.                                                //再将和进行装箱赋给x。  
  12.                    //x的拆箱过程    x.intValue()    
  13.    
  14.                    Integer m = 128;  
  15.                    Integer n = 128;  
  16.    
  17.                    sop("m==n:"+(m==n));  
  18.    
  19.                    Integer a = 127;  
  20.                    Integer b = 127;  
  21.    
  22.                    sop("a==b:"+(a==b));//结果为true。因为a和b指向了同一个Integer对象。  
  23.                                                         //因为当数值在byte范围内容,对于新特性,如果该数值已经存在,则不会在开辟新的空间。  
  24.          }  
  25.    
  26.          public static void method()  
  27.          {  
  28.                    Integer x = new Integer("123");  
  29.    
  30.                    Integer y = new Integer(123);  
  31.     
  32.                    sop("x==y:"+(x==y));  
  33.                    sop("x.equals(y):"+x.equals(y));  
  34.          }  
  35.    
  36.          public static void sop(String str)  
  37.          {  
  38.                    System.out.println(str);  
  39.          }  
  40.           
  41. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值