Java学习笔记1——String类

来源:互联网 发布:js中new 关键字 编辑:程序博客网 时间:2024/05/18 12:00

一、String类
1、概念:字符串,是多个字符组成的一串数据。
位于java.lang包。
String类是一个被final修饰的类,表示不可被继承和修改。字符串的底层存储结构是char数组。

public final class String{...}

2、部分的构造函数
(1)空构造函数:String()
初始化一个新的空字符串对象

String str = new String();

(2)以String对象为参数:String(String string)

创建一个String类对象s,并将一个字符串str赋予新的String对象s

String s = new String("str");

(3)以字符数组为参数构造String:String(char value[])

创建一个String对象,将chs传入赋予s

char[] chs = {'a','b','c'};String s = new String(chs);

(4)传入字符数组的子数组:String(char value[], int offset, int count)
将字符数组value(chs)从第offset位开始,传入长度为count的子数组构造成字符串s。

char[] chs = {'a','b','c','d','e'};String s = new String(chs,1,3);

(5)传入整型int数组的子数组,构造对应字符的字符串:String(int[] codePoints, int offset, int count)
传入的数组为整型数组,将为转换为ASCII对应的字符。

int[] chs = {65,66,67,68,97,97};String s = new String(chs,1,3);

(6)传入字节数组的子数组构建String对象:public String(byte bytes[], int offset, int length)
传入一个字节数组,从第offset个位置开始,取长度为length的子数组,构建一个新的字符串s。

byte[] chs = {1,2,3,4,5};String s = new String(chs,1,3);

(7)传入字节数组构建String对象:public String(byte bytes[])
传入一个字符数组,构建一个新的字符串对象s。

byte[] chs = {1,2,3,4,5};String s = new String(chs);

此构造方法是通过调用this(bytes, 0, bytes.length);即上述(6)的方法。

(8)传入字符数组,以指定编码构造字符串:public String(byte bytes[], int offset, int length, String charsetName)
指定编码传入字符数据构造字符串。

byte[] chs = {61,66,60,68,97,97};String s = new String(chs,1,3,"GBK");

(9)传入StringBuffer并将转化为String:public String(StringBuffer buffer)
传入StringBuffer,调用toString()方法转化为字符串。

StringBuffer buffer = new StringBuffer("Hello World!");String s = new String(buffer);

(10)传入StringBuilder并转化为String:public String(StringBuilder builder)
传入StringBuilder,调用toString()方法转化为字符串。与(9)同理。

StringBuilder builder = new StringBuilder("Hello World!");String s = new String(builder);

3、常用方法
A:判断方法
(1)判断字符串的内容是否相同,区分大小写:public boolean equals(Object obj)
(2)判断字符串的内容是否相同,区分大小写:public boolean equalsIgnoreCase(String str)
(3)判断字符串对象是否包含指定的字符串:public boolean contains(String str)
(4)判断字符串对象是否以指定的字符串开始:public boolean startsWith(String str)
(5)判断字符串对象是否以指定的字符串结尾:public boolean endsWith(String str)
(6)判断字符串对象或数据是否为空:public boolean isEmpty()
(7)获取指定位置的字符的ACSII码:public int codePointAt(int index)
(8)获取指定位置的前一个字符的ACSII码:public int codePointBefore(int index)

例子:

public class StringDemo {      public static void main(String[] args) {          // 创建字符串对象          String str = "Hello World!";          // boolean equals(Object obj)        // 判断字符串内容是否相同,区分大小写        System.out.println(s.equals("Hello World!"));          System.out.println(s.equals("hello world!"));          System.out.println("--------------------");          // boolean equalsIgnoreCase(String str)        // 判断字符串内容是否相同,不区分大小写        System.out.println(s.equalsIgnoreCase("Hello World!"));        System.out.println(s.equalsIgnoreCase("Hello World!"));         System.out.println("--------------------");          // boolean contains(String str)        // 判断字符串对象是否包含指定的字符串        System.out.println(s.contains("llo"));          System.out.println(s.contains("orr"));          System.out.println("--------------------");          // boolean startsWith(String str)        // 判断字符串对象是否以指定的字符串开始          System.out.println(s.startsWith("Hel"));          System.out.println(s.startsWith("hello"));          System.out.println("--------------------");          // boolean endsWith(String str)        // 判断字符串对象是否以指定的字符串结束          System.out.println(s.endsWith("orld!"));          System.out.println(s.endsWith("world!"));          System.out.println("--------------------");          // boolean isEmpty()        // 判断字符串对象或数据是否为空        System.out.println(s.isEmpty());          String s2 = "";          System.out.println(s2.isEmpty());          // String s3 = null;          // NullPointerException 空指针异常          // System.out.println(s3.isEmpty());      }  }  

B:获取方法
(1)获取字符串的长度:public int length()
(2)获取指定字符在此字符串中第一次出现的位置:public int indexOf(int ch)
(3)获取指定字符串在此字符串中第一次出现的位置:public int indexOf(String str)
(4)获取在此字符串中第一次出现指定字符的位置,从指定的位置开始搜索:public int indexOf(int ch,int fromIndex)
(5)获取在此字符串中第一次出现指定字符串的位置,从指定的位置开始搜索:public int indexOf(String str,int fromIndex)
(6)获取在此字符串中最后出现的指定字符串的位置:public int lastIndexOf(String str)
(7)lastIndexOf的其他不同方法与indexOf类似
(8)获取字符串中指定位置的字符:char charAt(int index)
(9)获取从指定位置开始到最后的字符串:String substring(int start)
(10)获取指定范围的字符串:public String substring(int beginIndex, int endIndex)
(11)将字符串按照指定规则进行切割,获得一个切割后的字符串数组:public String[] split(String regex)
(12)去除两端空格:public String trim()

例子:

public class StringDemo {    public static void main(String[] args) throws UnsupportedEncodingException {        String s = "Hello World!";        // int length()        // 获取字符串的长度        System.out.println(s.length());        System.out.println("--------------");        // char charAt(int index)        System.out.println(s.charAt(2));          System.out.println("--------------");        // int indexOf(int ch)        System.out.println(s.indexOf('o'));        System.out.println("--------------");        // int indexOf(int ch,int fromIndex)        System.out.println(s.indexOf('o', 5));        System.out.println("--------------");        // int lastIndexOf(int ch)        System.out.println(s.lastIndexOf('o'));        System.out.println("--------------");        // int lastIndexOf(int ch,int fromIndex)        System.out.println(s.lastIndexOf('o', 5));        System.out.println("--------------");        // String substring(int start)         System.out.println(s.substring(4));          // String substring(int start,int end)        System.out.println(s.substring(4, 8));          System.out.println("--------------");        // String[] spilt(String regex)        String strs = "hello|world|hey"        System.out.println(s.spilt("|"));    }}

C:转换功能
(1)把字符串转换成字节数组:public byte[] getBytes()
(2)把字符串转换成字符数组:public char[] toCharArray()
(3)把字符数组转换成字符串:public static String copyValueOf(char[] chs)
(4)把字符数组转换成字符串:public static String valueOf(char[] chs)
(5)把int(基本类型)转换成字符串:public static String valueOf(int i)
(还有其他基本类型的转换)
(6)把字符串变成小写:String toLowerCase()
(7)把字符串变成大写:String toUpperCase()
(8)拼接字符串:String concat(String str)

例子:

public class StringDemo {      public static void main(String[] args) {          // 创建字符串对象          String s = "Hello World!";          // byte[] getBytes()        byte[] bys = s.getBytes();          for (int x = 0; x < bys.length; x++) {              System.out.println(bys[x]);          }          System.out.println("-----------------");          // char[] toCharArray()          char[] chs = s.toCharArray();          for (int x = 0; x < chs.length; x++) {              System.out.println(chs[x]);          }          System.out.println("-----------------");          // static String copyValueOf(char[] chs)        char[] chs2 = { '大', '佬', 's', 'n', 'm' };          String s2 = String.copyValueOf(chs2);          System.out.println(s2);          System.out.println("-----------------");          // static String valueOf(char[] chs)          String s3 = String.valueOf(chs2);          System.out.println(s3);          System.out.println("-----------------");          // static String valueOf(int i)          int i = 666;          String s4 = String.valueOf(i);          System.out.println(s4);          System.out.println("-----------------");          // String toLowerCase()        System.out.println(s.toLowerCase());          // String toUpperCase()         System.out.println(s.toUpperCase());          System.out.println("-----------------");          // String concat(String str)         String s5 = "hello";          String s6 = s5 + "world";          String s7 = s5.concat("world");          System.out.println(s6);          System.out.println(s7);      }  }  

D:替换功能
(1)用新的字符去替换指定的旧字符:String replace(char oldChar,char newChar)
(2)用新的字符串去替换指定的旧字符串:String replace(String oldString,String newString)

例子:

public class StringDemo {      public static void main(String[] args) {          // 创建字符串对象          String s1 = "Hello";          String s2 = "Hello";        //char与String的区别在于单引号与双引号        System.out.println(s1.replace('H', 's'));           System.out.println(s2.replace("H", "S"));       }  }  

E:字典顺序比较功能
(1)返回前后比较的两个字符串的ACSII码的差值:public int compareTo(String str)
如果两个字符串首字母不同,则该方法返回首字母的ACSII码的差值
(2)忽略大小写,返回前后比较的两个字符串的ACSII码的差值:public int compareToIgnoreCase(String str)

例子:

public class StringDemo {      public static void main(String[] args) {          // 创建字符串对象          String s1 = "Hello";          String s2 = "hello";        String s3 = "aello";        String s4 = "Helle";        System.out.println(s1.compareTo(s2));   //-32        System.out.println(s1.compareTo(s3));   //-25        System.out.println(s1.compareTo(s4));   //10        System.out.println("----------------------");        System.out.println(s1.compareToIgnoreCase(s2));     //0        System.out.println(s1.compareToIgnoreCase(s3));     //7        System.out.println(s1.compareToIgnoreCase(s4));     //10    }  }  

二、常见问题
1、字符串比较
这里可以包括了其他类型的比较,此处仅用String。

String s1 = "hello";String s2 = "hello";String s3 = new String("hello");String s4 = new String(s1);System.out.println(s1==s2);//trueSystem.out.println(s1==s3);//falseSystem.out.println(s1==s4);//falseSystem.out.println(s3==s4);//falseSystem.out.println(s1.equals(s3));//trueSystem.out.println(s1.equals(s4));//true

第一个:s1==s2。结果为true,s1和s2引用的“hello”是常量,在常量池中,故是true。
第二个:s1==s3。结果为false,s3是通过new创建的对象,存放在堆内存中,所以比较时不一样。
第三个:s1==s4。结果为false,同理。
第四个:s1.equals(s3)。结果为true。equals是比较两者内容是否相同。
第五个:s1.equals(s4)。结果为true,同理。

2、String的内容是否能够改变?
这个涉及到了final。final修饰后,指的是,引用变量不能变,引用变量所指向的对象中的内容还是可以改变的。
通常看到修改的String内容,只是String修改了内容指向,原本的内容并未改变。

3、String s = new String(“abc”)创建了多少个String对象?
两个或一个,”abc”对应一个对象,这个对象放在字符串常量缓冲区,常量”abc”不管出现多少遍,都是缓冲区中的那一个。new String每写一遍,就创建一个新的对象,它一句那个常量”abc”对象的内容来创建出一个新String对象。如果以前就用过’abc’,这句代表就不会创建”abc”自己了,直接从缓冲区拿。

4、String和StringBuilder和StringBuffer的区别
String、StringBuilder和StringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。
这个String类提供了数值不可改变的字符串。而这个StringBuilder和StringBuffer类提供的字符串进行修改。
String覆盖了equals方法和hashCode方法,而StringBuffer没有覆盖equals方法和hashCode方法,所以,将StringBuffer对象存储进Java集合类中时会出现问题。
StringBuilder和StringBuffer的区别是是否安全等等。
当需要频繁修改字符串的时候,建议使用StringBuffer。
单线程操作时推荐使用StringBuilder,效率更高。
多线程时操作推荐使用StringBuffer,更加安全。

5、对乱序的字符串(字符串中的字符是乱序的)进行排序

public class StringDemo {      public static void main(String[] args) {          String s = "xzcnjeum";        char[] chs = s.toCharArray();        //排序方法不限        for(int i = 0;i<chs.length;i++){            for (int j = 0; j < chs.length - 1 - i; j++) {                  if (chs[j] > chs[j + 1]) {                      char ch = chs[j];                      chs[j] = chs[j + 1];                      chs[j + 1] = ch;                  }              }          }        System.out.println(chs);    }  }  

当然还有很多没有写好,也是第一次写学习笔记,如果有什么问题欢迎指出。

原创粉丝点击