String 类

String类

目录

String类

字符常量  -- String类型的对象

空字符串与null

 String类的声明 及字段

构造函数

String的静态方法

静态: 将参数转换成String类型  valueOf

实例方法

1.与其他类比较内容是否相等  

2.判断字符串是否包含指定序列

3.比较compare

4.取子串

5.索引

6.替代 replace

7.String 与其他类型的转换方法

         8. String 之间 特殊转换

9.根据索引将目标字符转换成codePoint

 indexOf源码


toString() 方法与 "+"

对于基本类型 可以通过 "+" 而不能调用toString()方法

字符串类 java中字符串 不是以 '\0'结尾的

String 类实现了三个接口 (须记住实现了CharSequence)

  • 字符常量  -- String类型的对象

被共享的地方 称为 字符常量池

System.out.println("123456".length() );//6
String constantStr1  ="constant"; // constantStr1引用 指向字符常量线程池
String constantStr2  ="constant"; // constantStr2引用 指向字符常量线程池
System.out.println( constantStr1 == constantStr2 ); //true
// 它们指向的是字符常量线程池中同一内容 故内存地址相同

char [] ch = {'n','e','w'};
String newStr1  = new String (ch);
String newStr2  = new String (ch);
System.out.println( newStr1  == newStr2 ); //false
//new关键字 创建对象(申请的不同内存地址) 
  • 空字符串与null

  • String str1 = new String() ;
    String str2 = null ; //引用为null
    String str3 = "" ;

  可知仅有 str1和str3的值相等(String的默认值)  内存地址均不同

 

 

  •  String类的声明 及字段

public final class String  implements java.io.Serializable, Comparable<String>, CharSequence{
 //字段
 private final char value[]; //实际通过封装字符数组 不可变性
 private int hash;  //默认0 设长度为n hash = v[0]*31^(n-1) + v[1]*31^(n-2)+...+v[n-1]        
/*       31的原因是 可以产生更分散的散列 计算效率高 31*h = (h<<5)-h 用高效移位和减法代替乘法
 * hash 的值:
 * 截取hashCode()
 * int h = hash;
 * for (int i = 0; i < value.length; i++) {
 *               h = 31 * h + val[i];
 *          }   
 */      
 private static final long serialVersionUID = -6849794470754667710L; 
 private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];
....
}
  • 构造函数

(除已过时的两个 还剩13个构造函数   6个byte[] 2个char[] 1个int[](代码点数组) 1个创建为空 )

String()//初始化新创建的String对象,使其表示空字符序列。
String(String)//新创建的字符串是参数字符串的副本。
String(StringBuilder)
String(StringBuffer)

2个char []
String(char[]){//以char[]初始化新创建的String对象
   this.value = Arrays.copyOf(value, value.length);
 }
String(char value[], int offset, int count) //从 offset开始长度为length 截取数组构造string对象

6个 byte[]相关的构造函数
String(byte[])//String通过使用平台的默认字符集解码指定的字节数组来构造new 。
String(byte bytes[], int offset, int length) //从 offset开始长度为length 截取数组构造string对象
//String通过使用指定的字符集解码指定的字节数组构造一个new 。
String(byte[], String)
String(byte[], Charset)
String(byte[] bytes, int offset, int length, String charsetName)
String(byte[] bytes, int offset, int length, Charset charset)

//int类型的codepoint数组转化为String
String(int[] codePoints, int offset, int count)

String的静态方法

public static String

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

valueOf(char[],int,int)

 
copyValueOf(char[] data)valueOf(char[] ) 
join(CharSequence delimiter,CharSequence... elements)

返回一个新的String,它由 CharSequenceelements连接的副本和指定的副本组成delimiter

注意:char不是CharSequence,delimiter必须是双引号

 
join(CharSequencedelimiter, Iterable<? extends CharSequence> elements) 

静态: 将参数转换成String类型  valueOf

valueOf(boolean b)return b ? "true" : "false";
valueOf(char c)return new String(data, true);可见性default的 构造函数,第二个参数用来区分public String(char[] c)

String valueOf(xxx  i)

//xxx: int long  float double

return Xxx.toString(i); 
format(Locale l, String format, Object... args)使用指定的语言环境,格式字符串和参数返回格式化的字符串 
format(String format, Object... args)使用指定的格式字符串和参数返回格式化字符串 
 
private boolean nonSyncContentEquals(AbstractStringBuilder sb)

仅被contentEquals(CharSequence cs)调用

针对对StringBuffer类型的内容比较进行加锁

private int indexOfSupplementary(int ch, int fromIndex)

仅被indexOf(int , int )调用

处理(罕见的)带有补充字符的indexOf调用

 private intlastIndexOfSupplementary(int ch, int fromIndex)

仅被lastIndexOf(int , int )调用

处理(罕见的)带有补充字符的indexOf调用 

 

实例方法

1.与其他类比较内容是否相等  

booleancontentEquals(CharSequencecs)

将此字符串与指定字符串进行比较CharSequence

equals不同 (仅能比较同为String类型)

contenEquals 包含equals(在String类型被其调用)

可判断自定义实现其CharSequence接口的类的比较

contentEquals(StringBuffer sb)

将此字符串与指定字符串进行比较StringBuffer

调用

contentEquals(CharSequencecs)

实现其功能

booleanequals(Object anObject)

将此字符串与指定的对象进行比较。

覆盖Object类
booleanequalsIgnoreCase(String anotherString)

将此String与另一个进行比较String忽略大小写

return (this == anotherString) ? true  : (anotherString != null)     && (anotherString.value.length == value.length)
            && regionMatches(true, 0, anotherString, 0, value.length);

booleanregionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等。ignoreCase为true忽略大小写

booleanregionMatches(int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等。

2.判断字符串是否包含指定序列

3.比较compare

booleancontains(CharSequence s)

当且仅当此字符串包含指定的char值序列时,才返回true。

intcompareTo(String anotherString)

按字典顺序比较两个字符串。

booleanstartsWith(String prefix)

测试此字符串是否以指定的前缀开头

intcompareToIgnoreCase(String str)

按字典顺序比较两个字符串,忽略大小写差异。

booleanstartsWith(String prefix, int toffset)

测试从指定索引开始的此字符串的子字符串是否以指定的前缀开头

 

4.取子串

 

booleanendsWith(String suffix)

测试此字符串是否以指定的后缀结尾

CharSequencesubSequence(int beginIndex, int endIndex)

返回作为此序列的子序列的字符序列。

 return this.substring(beginIndex, endIndex);

booleanmatches(String regex)

判断此字符串是否与给定的正则表达式匹配。

Stringsubstring(int beginIndex)
substring(int beginIndex, int endIndex)
booleanisEmpty()

true当且仅当length()返回0,。

subString() 的实现 调用构造函数

String (char value[],int offset,int count)

5.索引

charcharAt(int index)

返回char指定索引处的值。

indexOf/lastIndexOf

返回参数第一次/最后一次出现的字符数组中的索引

1indexOf(int ch)

(从字符数组中的下标为0的位置开始)。

ch 是作为字符型对应的整型编码, 

indexOf(String str)

返回指定子字符串第一次出现的字符串中的索引。

2

indexOf(int ch, int fromIndex)

(从字符数组中的下标为fromIndex的位置开始)。

indexOf(String str, int fromIndex)

从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。

1.1lastIndexOf(int ch)

返回指定字符最后一次出现的字符串中的索引。

lastIndexOf(String str)

返回指定子字符串最后一次出现的字符串中的索引。

2.1lastIndexOf(int ch, int fromIndex)

返回指定字符最后一次出现的字符串中的索引,从指定的索引开始向后搜索。

lastIndexOf(String str, int fromIndex)

返回指定子字符串最后一次出现的字符串中的索引,从指定索引开始向后搜索。

 

6.替代 replace

Stringreplace(char oldChar, char newChar)

返回通过替换oldChar此字符串中出现的所有匹配项而产生的 字符串newChar

Stringreplace(CharSequence target,CharSequence replacement)

将此字符串中与文字目标序列匹配的每个子字符串替换为指定的文字替换序列。

StringreplaceAll(String regex, String replacement)

将给定替换的给定正则表达式匹配的此字符串的每个子字符串替换。

StringreplaceFirst(String regex, String replacement)

将给定替换的给定正则表达式匹配的此字符串的第一个子字符串替换。

7.String 与其他类型的转换方法

char[]->StingString(char [] )构造函数
Sting ->char[]

返回 char[]  方法: toCharArray()

toCharArray()将此字符串转换为新的字符数组。

public  void  getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 

将此字符串中[srcBegin srcEnd-1]的字符 复制到目标字符数组[dstBegin , ..]中

注意char [] 长度是固定, 若在复制过程中超出字符数组的长度将引起

java.lang.ArrayIndexOutOfBoundsException

void getChars(char dst[], int dstBegin)
 //可见性 缺省

方法内容:System.arraycopy(value, 0, dst, dstBegin, value.length);

将当期字符数组value(即当前字符串) 的 [0,value.length-1]

复制到 dst 的[dstBegin,dstBegin+value.length-1]

Sting -> byte []返回 byte[]   方法: getBytes()
getBytes(String charsetName)

String使用命名的字符集将其编码为字节序列,将结果存储到新的字节数组中。

getBytes()

String使用平台的默认字符集将其编码为字节序列,将结果存储到新的字节数组中

应用: "abc" -> 97 98 99

getBytes(Charset charset)

String使用给定的字符集将其编码为字节序列 ,将结果存储到新的字节数组中

8. String 之间 特殊转换

将String转换成 大/小的形式
String toLowerCase()String使用默认语言环境的规则将此中的所有字符转换为小写。
String toLowerCase(Locale locale)String使用给定的规则将此中的所有字符转换为小写Locale
String toUpperCase()=String使用默认语言环境的规则将此中的所有字符转换为大写。
String toUpperCase(Locale locale)String使用给定的规则将此中的所有字符转换为大写Locale
  
String trim()返回一个字符串,其值为此字符串,并删除任何前导和尾随空格。
void  getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 将此字符串中的字符复制到目标字符数组中。
String concat(String str)将指定的字符串连接到此字符串的末尾
将此字符串拆分为给定正则表达式的匹配项。
String[] split(String regex)按regex正则 将字符串切割成String []
String[] split(String regex, int limit)

9.根据索引将目标字符转换成codePoint

int   offsetByCodePoints(int index, int codePointOffset)

返回此范围内的索引,该索引String偏离代码点给定index的 codePointOffset值。

  public native String intern();返回字符串对象的规范表示
int codePointAt(int index)

返回指定索引处的字符(Unicode代码点)。

int codePointBefore(int index)

返回指定索引之前的字符(Unicode代码点)。

int codePointCount

(int beginIndex, int endIndex)

返回指定文本范围内的Unicode代码点数String

 

indexOf源码

/*
 *indexOf(String str)中调用 index(String ,int fromIndex) 给fromIndex传入0
 *String str中str为目标字符串
 */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, 0, value.length,
                str.value, 0, str.value.length, fromIndex);
    }
   /*
    *该方法为静态 可见性为缺省  作用:针对目标为字符串String类
    *被 AbstractStringBuilder类中indexOf()方法所调用
    */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
            String target, int fromIndex) {
        return indexOf(source, sourceOffset, sourceCount,
                       target.value, 0, target.value.length,
                       fromIndex);
    }
      /*
       *实现完成 indexOf()方法中与Sting有关的操作
       *该方法为静态 可见性为缺省
       *下面将被搜索的字符数组 称为主串
       *char[] source 主串                  被调用方的方法填充
       *sourceOffset 主串的起始位置      被调用方的方法填充 0
       *sourceCount  主串的长度             被调用方的方法填充 count
       * #target        目标字串
       *  targetOffset 目标字串的起始位置    被调用方的方法填充 0
       *  targetCount  目标串的长度          被调用方的方法填充 target.count
       * #fromIndex     开始搜索的位置相对于目标字串的起始位置
       *
       *返回值 -1  意味着 主串中不含目标字串
       *      >=0 意味着  主串中含有目标字串
       *     返回主串中目标字串出现的下标位置
       *      若目标字符为空 则返回主串的fromIndex 若fromIndex>sourceCount-1 则返回sourceCount
       */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
            char[] target, int targetOffset, int targetCount,
            int fromIndex) {
        if (fromIndex >= sourceCount) { //开始位置大于主串的最大有效位置(sourceCount-1)
            return (targetCount == 0 ? sourceCount : -1);//若目标字串不为空,则返回-1 
        }
        if (fromIndex < 0) { //若fromIndex >= sourceCount 则意味着 有效字串实际上为空
            fromIndex = 0;
        }
        if (targetCount == 0) {
            return fromIndex;
        }

        char first = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);
       //以source[i] == targetOffset 作为判断进入循环的条件 
        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }

            /* Found first character, now look at the rest of v2 */
            if (i <= max) { //之前的while循环的判断条件 i先自增再判断 所以
                int j = i + 1;//i已遍历
                int end = j + targetCount - 1;//遍历完target时的主串下标的位置
        //进入循环 
        //  退出循环:元素不一致或遍历完目标字串
                for (int k = targetOffset + 1; j < end && source[j]
                        == target[k]; j++, k++);//k标记
           //若循环遍历完目标字串
                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值