Java String 构造器 方法

Java String

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

*The {@code String} class represents character strings. All
* string literals in Java programs, such as {@code "abc"}, are
* implemented as instances of this class.
{@code String} 类表示字符串。 
Java 程序中的所有字符串文字,例如 {@code "abc"},
都被实现为此类的实例。

字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。String底层是一个char类型的数组。private final char value[];

例如: "abc"就是String类下的一个具体的对象
String str = "abc";

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

构造器

底层就是给对象底层的value数组进行赋值操作

String()
初始化一个新创建的 String 对象,使其表示一个空字符序列。

byte[]

String(byte[] bytes[, int offset, int length][, Charset charset])
通过使用指定的charset解码(未指定则使用平台默认字符集)指定的 byte 子数组,构造一个新的 String。

  • bytes- 要解码为字符的 byte
  • offset- 要解码的第一个 byte 的索引
  • length- 要解码的 byte 数
  • charset- 用来解码 bytes 的 charset

String(byte[] bytes[, int offset, int length], String charsetName)
通过使用指定的字符集解码指定的 byte 子数组,构造一个新的 String。

  • charsetName- 受支持 *charset *的名称

char[]

String(char[] value)
分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
String(char[] value, int offset, int count)
分配一个新的 String,它包含取自字符数组参数一个子数组的字符。

  • value - 作为字符源的数组
  • offset - 初始偏移量
  • count - 长度

其他

String(int[] codePoints, int offset, int count)
分配一个新的 String,它包含 Unicode 代码点数组参数一个子数组的字符。

  • codePoints - 作为 Unicode 代码点的源的数组。

String(StringBuffer buffer)
分配一个新的字符串,它包含字符串缓冲区参数中当前包含的字符序列。
String(StringBuilder builder)
分配一个新的字符串,它包含字符串生成器参数中当前包含的字符序列。

public static void main(String[] args) {
    //通过构造器来创建对象:
    String s1 = new String();
    String s2 = new String("abc");
    String s3 = new String(new char[]{'a','b','c'});
}

方法

Type方法描述
charcharAt(int index)返回指定索引处的 char 值。
intcodePointAt(int index)返回指定索引处的字符(Unicode 代码点)。
intcodePointBefore(int index)返回指定索引之前的字符(Unicode 代码点)。
intcodePointCount(int beginIndex, int endIndex)返回此 String 的指定文本范围中的 Unicode 代码点数。
intcompareTo(String anotherString)按字典顺序比较两个字符串。相等则结果为 0
intcompareToIgnoreCase(String str)按字典顺序比较两个字符串,不考虑大小写。
Stringconcat(String str)将指定字符串连接到此字符串的结尾。
booleancontains(CharSequence s)当且仅当此字符串包含指定的 char 值序列时,返回 true。
booleancontentEquals(CharSequence cs)将此字符串与指定的 CharSequence 比较。
booleancontentEquals(StringBuffer sb)将此字符串与指定的 StringBuffer 比较。
static StringcopyValueOf(char[] data)返回指定数组中表示该字符序列的 String。
static StringcopyValueOf(char[] data, int offset, int count)返回指定数组中表示该字符序列的 String。offset - 子数组的初始偏移量。count - 子数组的长度。
booleanendsWith(String suffix)测试此字符串是否以指定的后缀结束。
booleanequals(Object anObject)将此字符串与指定的对象比较。
booleanequalsIgnoreCase(String anotherString)将此 String 与另一个 String 比较,不考虑大小写。
static Stringformat(Locale l, String format, Object... args)使用指定的语言环境、格式字符串和参数返回一个格式化字符串。
static Stringformat(String format, Object... args)使用指定的格式字符串和参数返回一个格式化字符串。
byte[]getBytes()使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
byte[]getBytes(Charset charset)使用给定的 charset将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
byte[]getBytes(String charsetName)使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
inthashCode()返回此字符串的哈希码。
intindexOf(int ch[, int fromIndex])返回在此字符串中第一次出现指定字符处的索引,fromIndex存在则从指定的索引开始搜索。
intindexOf(String str[, int fromIndex)]返回指定子字符串在此字符串中第一次出现处的索引,fromIndex存在则从指定的索引开始。
Stringintern()返回字符串对象的规范化表示形式。
booleanisEmpty()当且仅当 length()0 时返回 true
intlastIndexOf(int ch, int fromIndex)返回指定字符在此字符串中最后一次出现处的索引,fromIndex存在则从指定的索引处开始进行反向搜索。
intlastIndexOf(String str, int fromIndex)返回指定子字符串在此字符串中最后一次出现处的索引,fromIndex存在则从指定的索引开始反向搜索。
intlength()返回此字符串的长度。
booleanmatches(String regex)告知此字符串是否匹配给定的正则表达式。
intoffsetByCodePoints(int index, int codePointOffset)返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。
Stringreplace(char oldChar, char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
Stringreplace(CharSequence target, CharSequence replacement)使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。
StringreplaceAll(String regex, String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
StringreplaceFirst(String regex, String replacement)使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
booleanstartsWith(String prefix[, int toffset)]测试此字符串(从指定索引开始的子字符串)是否以指定前缀开始。
CharSequencesubSequence(int beginIndex, int endIndex)返回一个新的字符序列,它是此序列的一个子序列。
Stringsubstring(int beginIndex[, int endIndex)]返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex处开始,直到索引 endIndex- 1 处的字符。无endIndex则直到此字符串末尾。
char[]toCharArray()将此字符串转换为一个新的字符数组。
StringtoLowerCase()使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
StringtoLowerCase(Locale locale)使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
StringtoString()返回此对象本身(它已经是一个字符串!)。
StringtoUpperCase()使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
StringtoUpperCase(Locale locale)使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
Stringtrim()返回字符串的副本,忽略前导空白和尾部空白。
static StringvalueOf(boolean b)返回 boolean 参数的字符串表示形式。
static StringvalueOf(char c)返回 char 参数的字符串表示形式。
static StringvalueOf(char[] data)返回 char 数组参数的字符串表示形式。
static StringvalueOf(char[] data, int offset, int count)返回 char 数组参数的特定子数组的字符串表示形式。
static StringvalueOf(double/float/ int/long d/f/i/l)返回 double/float/int/long 参数的字符串表示形式。
static StringvalueOf(Object obj)返回 Object 参数的字符串表示形式。
  • String[] split(String regex[, int limit)]

    • 根据匹配给定的正则表达式来拆分此字符串。

    • limit - 结果阈值,控制模式应用的次数。

      n > 0,则模式将被最多应用 n - 1 次,数组的长度将不会大于 n,而且数组的最后一项将包含所有超出最后匹配的定界符的输入。

      n <= 0,则模式将被应用尽可能多的次数,而且数组可以是任何长度。

      n = 0,则模式将被应用尽可能多的次数,数组可以是任何长度,并且结尾空字符串将被丢弃。

      调用此方法的 str.split(regex, n)形式与Pattern.compile(regex).split(str, n)产生的结果完全相同。字符串 “boo:and:foo” 使用这些参数可生成以下结果:

      RegexLimit结果
      :2{ “boo”, “and:foo” }
      :5{ “boo”, “and”, “foo” }
      :-2{ “boo”, “and”, “foo” }
      o5{ “b”, “”, “:and:f”, “”, “” }
      o-2{ “b”, “”, “:and:f”, “”, “” }
      o0{ “b”, “”, “:and:f” }
  • boolean regionMatches([boolean ignoreCase, ]int toffset, String other, int ooffset, int len)

    • 测试两个字符串区域是否相等。
    • ignoreCase - 如果为 true,则比较字符时忽略大小写。
    • toffset - 此字符串中子区域的起始偏移量。
    • other - 字符串参数。
    • toffset - 字符串参数中子区域的起始偏移量。
    • len - 要比较的字符数。

    当且仅当下列至少一项为 true 时,结果才为 false:

    • toffsetooffset为负。
    • toffset+len 大于此 String 对象的长度
    • ooffset+len 大于另一个参数的长度。
    • ignoreCase 为 false时对应位置 this.charAt(toffset+k) != other.charAt(ooffset+k)
    • ignoreCase 为 true时,对应位置大小写同步后char不同
  • void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

    将字符从此字符串复制到目标字符数组。要复制的第一个字符位于索引 srcBegin 处;要复制的最后一个字符位于索引 srcEnd-1 处(因此要复制的字符总数是 srcEnd - srcBegin)。要复制到 dst 子数组的字符从索引 dstBegin 处开始,并结束于索引:dstbegin + (srcEnd-srcBegin) - 1

    • srcBegin - 字符串中要复制的第一个字符的索引。
    • srcEnd- 字符串中要复制的最后一个字符之后的索引。
    • dst- 目标数组。
    • dstBegin - 目标数组中的起始偏移量。

实例

长度相关
String s1 = "abc";
System.out.println("字符串的长度为:"+s1.length()); //3
String s2 = new String("abc");
System.out.println("字符串是否为空:"+s2.isEmpty()); //false
System.out.println("获取字符串的下标对应的字符为:"+s2.charAt(1)); //b
比较相关
equals
  • 将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。

  • equals(Object anObject)源码

    public boolean equals(Object anObject) {
        if (this == anObject) { //两对象地址指向地址相同
            return true; //或自己与自己相比则直接true
        }
        if (anObject instanceof String) { //传入的是否为String类实例
            String anotherString = (String)anObject; //下转型为String
            int n = value.length; //比较长度,如果长度不同直接falsa
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0; //数组遍历,按位比较
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }
    
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); //true
compareTo
  • int compareTo(String anotherString) 按字典顺序比较两个字符串。

    • 两个字符串相等,则结果为 0;
    • 两个字符串在位置 k 处不同,返回两个char 值的差 this.charAt(k)-anotherString.charAt(k)
    • 没有字符不同的索引位置,返回这两个字符串长度的差,即值: this.length()-anotherString.length()
  • compareTo(String anotherString)源码

    public int compareTo(String anotherString) {
            int len1 = value.length; // 本字符串长度
            int len2 = anotherString.value.length;
            int lim = Math.min(len1, len2); //取较短字符串长度
            char v1[] = value; //本字符串给 v1字符数组
            char v2[] = anotherString.value; //外字符串给 v1字符数组
    
            int k = 0;
            while (k < lim) {
                char c1 = v1[k];
                char c2 = v2[k];
                if (c1 != c2) {
                    return c1 - c2; //不同位置字符的ASCII码差值
                }
                k++;
            }
            return len1 - len2; //返回结果为两字符串长度差值
    }
    
String s = new String("abc");
System.out.println(s.compareTo("abc")); //0
System.out.println(s.compareTo("ab")); //1
System.out.println(s.compareTo("abd")); //-1
重组
//字符串的截取:
String s10 = "abcdefg";
System.out.println(s10.substring(3)); //ddefg
System.out.println(s10.substring(3, 6));//def,[3,6)

//字符串的合并/拼接操作:
System.out.println(s10.concat("sss")); //abcdefgsss

//字符串中的字符的替换:
String s11 = "aabbcc";
System.out.println(s11.replace('a', 'd')); // ddbbcc

//按照指定的字符串进行分裂为数组的形式:
String s12 = "a-b-c-d-e-f";
String[] st = s12.split("-");
System.out.println(Arrays.toString(st)); //[a, b, c, d, e, f]
转换
//转大小写的方法:
String s13 = "abcDEF";
System.out.println(s13.toUpperCase()); //ABCDEF
System.out.println(s13.toLowerCase()); //abcdef

//忽略前导空白和尾部空白
String s14 = "    a  b    ";
System.out.println(s14.trim()); //a  b

//toString()
String s15 = "abc";
System.out.println(s15.toString()); //abc

//转换为String类型:
System.out.println(String.valueOf(true)); //true
posted @ 2021-08-09 23:31  SKPrimin  阅读(126)  评论(0编辑  收藏  举报