Java字符串转数组,数组转字符串

技术博客 (305) 2023-09-16 17:36:01

因为算法很多都是输入字符串做解析的,所以算法得必会以下三种方法

        //字符串转化为数组
        String str = "aa,bbb";
        //1.字符串转字符串数组
        String[] strArr = str.split(",");
        //2.字符串转char数组
        char[] charArr = str.toCharArray();
        //3.读取字符串下标为i的char
        char s = str.charAt(1);

样例

1.数字字符串转化为int数组

        String str2 = "123456";
        
        //方法一:通过charAt()可以获得对应下标的char值,用String.valueOf()转为字符串,
        //再用Integer.parseInt()转为数字
        int[] intArr2 = new int[str2.length()];
        for (int i = 0; i < intArr2.length; i++) { 
   
            intArr2[i] = Integer.parseInt(String.valueOf(str2.charAt(i)));
        }

        //方法二:先转为char[]在赋值给int[],效果同上,但多创建了一个char数组
        char[] charArr2 = str2.toCharArray();
        int[] intArr3 = new int[str2.length()];
        for (int i = 0; i < intArr2.length; i++) { 
   
            intArr3[i] = Integer.parseInt(String.valueOf(charArr2[i]));
        }

2.带分隔符数字字符串转化为int数组

        String str3 = "1,2,3,4,5";
        String[] strArr3 = str3.split(",");
        //分隔为字符数组后,只要循环String[]用Integer.parseInt()转为数字在赋值给int[]
        int[] intArr4 = new int[strArr3.length];
        for (int i = 0; i < strArr3.length; i++) { 
   
            intArr4[i] = Integer.parseInt(strArr3[i]);
        }

3.char[]转字符串

        char[] charArr3 = new char[]{ 
   '1','2','3','4','5'};
        //1.用String工具类,效率最高
        String charSring1 = String.valueOf(charArr3);
        //2.直接new Sring
        String charSring2 = new String(charArr3);

4.String[]转字符串

        String[] strings = new String[]{ 
   "12","34","56","aa"};
        //用StringBuilder(效率快)或者StringBuffer(线程安全),不要用+拼接浪费内存
        StringBuilder stringBuffer1 = new StringBuilder();
        for (String string : strings) { 
   
            stringBuffer1.append(string);
        }
        String s1 = stringBuffer1.toString();

int[]转字符串,同上

        int[] ints = new int[]{ 
   1,2,4,3};
        StringBuilder stringBuffer2 = new StringBuilder();
        for (int anInt : ints) { 
   
            stringBuffer2.append(anInt);
        }
        String s2 = stringBuffer2.toString();
THE END

发表回复