Java 中的String类

0.String简介:

String 类代表字符串。

字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的(为什么不可变?看到别人的,看起来很详细),所以可以共享。emm...为啥可以共享?查了下说在JVM里怎么怎么balabala...(这里还有待学习)

Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。

String str="abc"等效于:

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

1.String构造方法

(1)
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}

(2)

public String(byte[] bytes)

通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。新 String 的长度是字符集的函数,因此可能不等于 byte 数组的长度。

(3)
public String(byte[] bytes,Charset charset)

通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String

这种方法在刚学习Javaweb时应用很多,解决中文乱码(ISO-8859-1 ——> UTF-8)

例如:

  String result_str=new String(target_str.getBytes("ISO-8859-1"),"utf-8");

(4)通过StringBuffer和StringBuilder构造

public String(StringBuffer buffer)
public String(StringBuilder builder)

这俩种都是分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列。该字符串生成器的内容已被复制,后续对它的修改不会影响新创建的字符串。

2.常用方法

(1)获取字符串长度 

public int length();

(2)返回指定索引处的 字符

  public char charAt(int index)

(3)返回字符/字符串在一定条件下出现的索引

 public int indexOf(int ch)
 public int indexOf(int ch,int fromIndex)
 public int indexOf(String str)
 public int indexOf(String str,int fromIndex)

如果fromIndex小于0,会从0开始搜索,如果  fromIndex>str.lengtn(),会return -1,表示没有找到。(源码里这么规定的)    

问题:既然传入的字符:这里为什么用int类型
              'a'和97 都表示a

(4) 截取功能

 <1>从指定位置开始截取,默认截取到末尾,返回新的字符串

 public String substring(int beginIndex):

 <2>从指定位置开始到指定位置末尾结束,包前不包含后

public String substring(int beginIndex, int endIndex): 

(5)转换功能:  

<1>将字符串转换为字节数组

  public byte[] getBytes()

<2>将字符串转换成字符数组(重点)

public char[] toCharArray() :

<3>将任意数据转换成字符串(重点,类方法)

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
 public static String valueOf(char data[]) {
        return new String(data);
    }
public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }
public static String valueOf(int i) {
        return Integer.toString(i);
    }

......还有几种不一 一阐述了(可以在源码里查看)


<4>字符串中所有的字符转成小写

 public String toLowerCase():

<5>字符串中所有的字符变成大写  

public String toUpperCase():

(6)判断功能

<1>将此字符串与指定的对象比较

boolean equals(Object obj)

<2>将此 String 与另一个 String 比较,不考虑大小写

  boolean equalsIgnoreCase(String str)

<3>判断当前string中是否包含子字符串  (重点)

  boolean contains(String str):

<4>以当前str字符串开头(重点)

  boolean startsWith(String str):

<5>以当前str字符串结尾(重点)

  boolean endsWith(String str):

<6>判断字符串是否为空

  boolean isEmpty()


(7)String 的拼接功能

   public String concat(String str)

字符串的特有功能:拼接功能和+拼接符是一个意思


(8)String 的替换功能

public String replace(char oldChar/(String oldStr),char newChar/(String newStr))

(9)String 的去除俩端空格      

     public String trim();

(10)比较字符串大小

该比较基于字符串中各个字符的 Unicode 值

public int compareTo(String str)

如果参数字符串等于此字符串,则返回值 0;如果此字符串按字典顺序小于字符串参数,则返回一个小于 0 的值;如果此字符串按字典顺序大于字符串参数,则返回一个大于0的数。(本来以为大于0时返回的是字符串长度之差,辛亏动手写了一下发现并不是,查看文档后说是该比较基于字符串中各个字符的 Unicode 值

如有错误之处,望指正

猜你喜欢

转载自blog.csdn.net/Mr_L_h/article/details/84878585