记录一下Java String类的常用方法

  1.Java String类:

  String 类代表字符串,Java 程序中的所有字符串文字(例如“abc”)都被实现为此类的实例。也就是说,Java 程序中所有的双引号字符串,都是 String 类的对象。

  String 类在 java.lang 包下,所以使用的时候不需要导包!

  2.String类的方法

  我们经常需要使用到字符串,无论是数组转字符串,还是字符串的拼接,亦或是集合中数据组合成字符串,都需要不可避免的调用String类的各种方法.

  因此,总结了String类常用方法,方便使用。

  注:(方法分成了三类:构造方法,静态方法,接口方法;分别封装在了三个方法中。)

  

import javax.sound.midi.Soundbank;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * @Author:Duanzhenbiao
 * @Date:2020/10/25
 * @Description:
 */

public class StringMethods {

        // TODO: String 的各种方法.

    /**
     * 字符串的各种构造器方法
     */
    public static void StringConstructor() throws UnsupportedEncodingException {
        // 无参时:TODO: 构造函数:String()
        String str1 = new String();
        System.out.println("String()方法:" + str1);

        // 字节数组作为参数时:TODO:构造函数:String(bytes)
        byte[] bytes = {97,98,99,100};
        String str2 = new String(bytes);
        System.out.println("String(bytes)方法:" + str2);

        // 字节数组作为参数,指定编码做参数  TODO: 构造函数:String(byte[] bytes, Charset charset)
        String str3 =new String(bytes,"GBK");
        System.out.println("String(bytes,"GBK")方法:"+ str3);

        // 通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。TODO: 构造函数:String(byte[] bytes, int offset, int length)
        String str4 = new String(bytes,1,3);
        System.out.println("String(bytes,1,3)方法:"+str4);

        // 分配一个新的 String ,以便它表示当前包含在字符数组参数中的字符序列。 TODO: 构造函数:String(char[] value, int offset, int count)
        char[] chars = {'I',' ','L','o','v','e',' ','y','o','u','!'};
        String str5 = new String(chars,0,chars.length);
        System.out.println("String(chars,0,chars.length)方法:"+str5);

        //分配一个新的 String ,其中包含 Unicode code point数组参数的子阵列中的 字符 。  TODO: 构造函数:String(int[] codePoints, int offset, int count)
        int[] intArray = {1,2,3,4,5,6,7,8,9,0,10};
        String str6 = new String(intArray,0,intArray.length);
        System.out.println("String(intArray,0,intArray.length)方法:"+str6);

        //初始化新创建的String对象,使其表示与参数相同的字符序列; 换句话说,新创建的字符串是参数字符串的副本。 TODO: 构造函数:String(String original)
        String str7 = new String("DuanZhenBiao");
        System.out.println("String(String original) 方法:"+str7);

        //分配一个新的字符串,其中包含当前包含在字符串缓冲区参数中的字符序列。 TODO: 构造函数:String(StringBuffer buffer)
        StringBuffer sb = new StringBuffer();
        sb.append("stringBufferString");
        sb.append("-------BufferString");
        String str8 = new String(sb);
        System.out.println("String(StringBuffer buffer) 方法:"+str8);

        // 分配一个新的字符串,其中包含当前包含在字符串构建器参数中的字符序列 TODO: 构造函数:String(StringBuilder builder)
        StringBuilder sbder = new StringBuilder("first,");
        sbder.append("second,");
        sbder.append("third");
        String str9 = new String(sbder);
        System.out.println("String(StringBuilder builder)方法:" +str9);

    }

    /**
     * String 静态方法汇总.
     */
    public static void stringStaticMethod(){

        //copyValueOf(char[] data)
        char[] chars = {'a','b','c','D','E','F','G','H'};
        String staticStr1 = String.copyValueOf(chars);
        System.out.println(staticStr1);

        //copyValueOf(char[] data, int offset, int count)
        String staticStr2 = String.copyValueOf(chars,1,chars.length-1);
        System.out.println(staticStr2);

        //format(Locale l, String format, Object... args)
        String staticStr3 = String.format("Hello,%s","World");
        System.out.println(staticStr3);

        //join(CharSequence delimiter, CharSequence... elements) 返回一个新的字符串,由 CharSequence elements的副本组成,并附有指定的delimiter的 delimiter 。
        String staticStr4 = String.join("", "ab","cd","ef","gh");
        System.out.println(staticStr4);

        // join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
        ArrayList<String> text = new ArrayList<>();
        text.add("Java");
        text.add("is");
        text.add("fun");
        String staticStr5 = String.join("-",text);
        System.out.println(staticStr5);

        //valueOf(boolean b) 、valueOf(char c) 、valueOf(char[] data) 、valueOf(char[] data, int offset, int count)
        //valueOf(double d) 、valueOf(float f) 、valueOf(int i) 、valueOf(long l)、valueOf(Object obj)
        String staticStr6 = String.valueOf(true);
        String staticStr7 = String.valueOf('a');
        String staticStr8 = String.valueOf(new char[]{'a','c'});
        String staticStr9 = String.valueOf(10.1f);
        String staticStr10 = String.valueOf(10.12);

    }


    /**
     * 字符串的接口方法.
     */
    public static void stringInterfaceMethod(){

        // charAt(int index) :返回 char指定索引处的值。
        String str = "abcdefghijklmn";
        char c = str.charAt(2);
        System.out.println(c);

        //codePointAt(int index) :返回指定索引处的字符(Unicode代码点)。
        int it = str.codePointAt(3);
        System.out.println(it);

        //codePointBefore(int index) 返回指定索引之前的字符(Unicode代码点)。
        int before = str.codePointBefore(3);
        System.out.println(before);

        //codePointCount(int beginIndex, int endIndex) 返回此 String指定文本范围内的Unicode代码点数。
        int between = str.codePointCount(0,5);
        System.out.println(between);

        //compareTo(String anotherString) 按字典顺序比较两个字符串。
        int compareto = str.compareTo("abcdf");//其比较规则是:拿出字符串的第一个字符与参数的第一个字符进行比较,如果两者不等,比较结束,
        System.out.println(compareto);          // 返回两者的ascii差,即字符串的第一个字符减去参数的第一个字符的ascii码值,比如代码第五行的-1.如果相等,
                                                // 则比较第二个字符,以此类推。比较到最后还是相等的,方法返回值为0。


        //concat(String str) 将指定的字符串连接到该字符串的末尾。
        String str2 = str.concat("---xiaohong");
        System.out.println(str2);

        //contains(CharSequence s) 当且仅当此字符串包含指定的char值序列时才返回true。
        boolean boo = str.contains("fgh");
        System.out.println(boo);

        //contentEquals(CharSequence cs) 将此字符串与指定的CharSequence进行 CharSequence 。
        boolean str3 = str.contentEquals("abcdefghijklmn");//比较内容
        System.out.println(str3);

        //contentEquals(StringBuffer sb) 将此字符串与指定的StringBuffer进行 StringBuffer 。
        StringBuilder sb=new StringBuilder("abcdefghijklmn");
        boolean bo = str.contentEquals(sb);
        System.out.println(bo);

        //endsWith(String suffix) 测试此字符串是否以指定的后缀结尾。
        boolean booo = str.endsWith("mn");
        System.out.println(booo);

        //equals(Object anObject) 将此字符串与指定对象进行比较。
        boolean equal = str.equals("abcdefghijklmn");
        System.out.println(equal);

        //getBytes() 使用平台的默认字符集将此 String编码为字节序列,将结果存储到新的字节数组中。
        byte[] bytes = str.getBytes();
        for (Object object:bytes){
            System.out.print(object + " ");
        }

        char[] chars = new char[6];
        str.getChars(0,5,chars,0); // 没有返回值.
        System.out.println("拷贝的字符串为:");
        System.out.println(chars);

        //hashCode() 返回此字符串的哈希码
        System.out.println(str.hashCode());

        //indexOf(int ch)  indexOf(int ch, int fromIndex)、indexOf(String str)
        System.out.println(str.indexOf(97));
        System.out.println(str.indexOf(98,2));
        System.out.println(str.indexOf("fg"));

        //intern() 返回字符串对象的规范表示。
        System.out.println(str.intern());

        //isEmpty()
        System.out.println(str.isEmpty());

        //lastIndexOf(string s) 返回指定字符的最后一次出现的字符串中的索引。
        String strs = "ancfdgabcdsajkldsaabc";
        System.out.println(strs.lastIndexOf("abc"));

        //matches(String regex) 告诉这个字符串是否匹配给定的 regular expression 。
        String regx = "1[0-9]{2}";
        System.out.println("103".matches(regx));

        //replace(char oldChar, char newChar)返回从替换所有出现的导致一个字符串 oldChar在此字符串 newChar 。
        String newStr = str.replace("abc","xiaoming");
        System.out.println(newStr);

        //replaceAll(String regex, String replacement)
        String oldStr = "adsd1212343jkgdsl4324gjfdskl6545";
        String newString  = str.replace("\[0-9]+",oldStr);
        System.out.println(newString);

        //split(String regex) 将此字符串分割为给定的 regular expression的匹配。
        String[] strArray = oldStr.split("1");
        for (Object object:strArray){
            System.out.print(object + " ");
        }
        System.out.println();

        // startsWith(String prefix)
        boolean startWith = oldStr.startsWith("ads");
        System.out.println(startWith);

        //startsWith(String prefix, int toffset) 测试在指定索引处开始的此字符串的子字符串是否以指定的前缀开头。
        boolean substartWith = oldStr.startsWith("ds",1);
        System.out.println(substartWith);

        //substring(int beginIndex) ,返回一个字符串,该字符串是此字符串的子字符串。
        //substring(int beginIndex, int endIndex) 返回一个字符串,该字符串是此字符串的子字符串。
        System.out.println(oldStr.substring(2));
        System.out.println(oldStr.substring(2,7));

        //toCharArray() 将此字符串转换为新的字符数组。
        char[] charss = oldStr.toCharArray();
        System.out.println(charss);

        //toLowerCase() 将所有在此字符 String使用默认语言环境的规则,以小写。
        System.out.println("FDJKDLASJFGFGGFGjfdshajgfhsdjg".toLowerCase());

        //toUpperCase() 将所有在此字符 String使用默认语言环境的规则大写。
        System.out.println("gfjkdgjkfdjGJFDHSJKGFREIOTREdjsGFHSJFDKGfgdgjk".toUpperCase());

        //trim() 返回一个字符串,其值为此字符串,并删除任何前导和尾随空格。
        System.out.println("   dsalkjladsj afkdjalfdgfdhg    ".trim());

    }



    public static void main(String[] args) throws Exception{
        StringConstructor();
        stringStaticMethod();
        stringInterfaceMethod();
    }



}
原文地址:https://www.cnblogs.com/duanxiaobiao/p/13875600.html