Java 数组和字符串的转换--不能通过toString方法

Java数组与字符串转换

java数组->字符串

       java中所有的类,不管是java库里面的类,或者是你自己创建的类,全部是从object这个类继承的。object里有一个方法就是toString(),那么所有的类创建的时候,都有一个toString的方法。这个方法是干什么的呢?

首先我们得了解,java输出用的函数print();是不接受对象直接输出的,只接受字符串或者数字之类的输出。

Object类中的toString()方法的源代码如下:

    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
char[] data = {'a', 'b', 'c'};
System.out.println(data.toString());  //输出结果为[C@79fc7299
输出会去调用object类里面的toString 方法,根据源码可知,输出结果为[类型@哈希值]。

而数组类中并没有对此方法重写(override),仅仅是重载(overload)为类的静态方法(参见java.util.Arrays)。

所以,数组直接使用toString(),会去调用object类里面的toString方法,结果是[类型@哈希值]。

数组转字符串可以使用Arrays类中的toString方法Arrays.toString(data)。附上Arrays类的toString方法源码。但是由源码可知,这种方法的toString()是带格式的,也就是说输出的是[a, b, c]。

 /**
     * Returns a string representation of the contents of the specified array.
     * The string representation consists of a list of the array's elements,
     * enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are
     * separated by the characters <tt>", "</tt> (a comma followed by a
     * space).  Elements are converted to strings as by
     * <tt>String.valueOf(char)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>
     * is <tt>null</tt>.
     *
     * @param a the array whose string representation to return
     * @return a string representation of <tt>a</tt>
     * @since 1.5
     */
    public static String toString(char[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
如果仅仅想输出abc则需用以下两种方法:

  方法1:直接在构造String时转换。

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

  方法2:调用String类的方法转换。

        String.valueOf(data)
String类valueOf方法的源码如下,由源码可知,valueOf实际也是new String对象,和方法1一样

/**
     * Returns the string representation of the <code>char</code> array
     * argument. The contents of the character array are copied; subsequent
     * modification of the character array does not affect the newly
     * created string.
     *
     * @param   data   a <code>char</code> array.
     * @return  a newly allocated string representing the same sequence of
     *          characters contained in the character array argument.
     */
    public static String valueOf(char data[]) {
        return new String(data);
    }

java字符串->数组

   如果是 “字符串数组” 转 “字符串”,只能通过循环,没有其它方法 
    String str = "123abc";
    char[] arr = str.toCharArray();  //char数组
    for(int i =0;i<arr.length;i++)
        System.out.println(arr[i]);    //1 2 3 a b c
    String str = "123abc";    
    for(int i=0;i<str.length();i++)
        System.out.print(str.charAt(i));//也可以通过charAt()来读取输出

   String[] str = {"abc", "bcd", "def"};
   StringBuffer sb = new StringBuffer();
   for(int i = 0; i < str.length; i++){
         sb.append(str[i]);
}

参考 http://www.cnblogs.com/ningvsban/p/3955483.html
考 http://www.cnblogs.com/ningvsban/p/3955483.html






                
Java 中,有多种方式可以实现数组字符串并能将字符串逆转回数组,以下是几种常见的实现: ### 字符数组字符串转换逆转 对于字符数组,可以使用简单的循环来实现数组字符串字符串数组,同时也能实现字符串的逆转。 ```java public class ArrayStringConversion { // 字符数组字符串 public static String charArrayToString(char[] arr) { StringBuilder sb = new StringBuilder(); for (char c : arr) { sb.append(c); } return sb.toString(); } // 字符串逆转 public static String reverseString(String str) { return new StringBuilder(str).reverse().toString(); } // 字符串转字符数组 public static char[] stringToCharArray(String str) { return str.toCharArray(); } public static void main(String[] args) { char[] charArray = {'a', 'b', 'c', 'd'}; String str = charArrayToString(charArray); System.out.println("字符数组字符串: " + str); String reversedStr = reverseString(str); System.out.println("逆转后的字符串: " + reversedStr); char[] reversedArray = stringToCharArray(reversedStr); System.out.println("逆转字符串转回字符数组: " + new String(reversedArray)); } } ``` 上述代码中,`charArrayToString` 方法将字符数组转换字符串,`reverseString` 方法使用 `StringBuilder` 的 `reverse` 方法字符串进行逆转,`stringToCharArray` 方法字符串转换回字符数组。 ### 字节数组字符串转换逆转 对于字节数组,需要考虑编码问题,使用 `ISO-8859-1` 编码可以避免一些乱码问题。 ```java import java.io.UnsupportedEncodingException; public class ByteArrayStringConversion { // 字节数组字符串 public static String byteArrayToString(byte[] arr) { try { return new String(arr, "ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } // 字符串逆转 public static String reverseStringForByte(String str) { return new StringBuilder(str).reverse().toString(); } // 字符串转字节数组 public static byte[] stringToByteArray(String str) { try { return str.getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { byte[] byteArray = {97, 98, 99, 100}; String str = byteArrayToString(byteArray); System.out.println("字节数组字符串: " + str); String reversedStr = reverseStringForByte(str); System.out.println("逆转后的字符串: " + reversedStr); byte[] reversedArray = stringToByteArray(reversedStr); System.out.println("逆转字符串转回字节数组: " + java.util.Arrays.toString(reversedArray)); } } ``` 在上述代码中,`byteArrayToString` 方法使用 `ISO-8859-1` 编码将字节数组转换字符串,`reverseStringForByte` 方法字符串进行逆转,`stringToByteArray` 方法字符串使用 `ISO-8859-1` 编码转换回字节数组。 ### 其他类型数组(如整数数组) 对于其他类型的数组(如整数数组),可以使用分隔符将数组元素连接成字符串,再根据分隔符将字符串拆分为数组。 ```java import java.util.Arrays; public class IntArrayStringConversion { // 整数数组字符串 public static String intArrayToString(int[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i]); if (i < arr.length - 1) { sb.append(","); } } return sb.toString(); } // 字符串逆转 public static String reverseStringForInt(String str) { return new StringBuilder(str).reverse().toString(); } // 字符串转整数数组 public static int[] stringToIntArray(String str) { String[] strArray = str.split(","); int[] intArray = new int[strArray.length]; for (int i = 0; i < strArray.length; i++) { intArray[i] = Integer.parseInt(strArray[i]); } return intArray; } public static void main(String[] args) { int[] intArray = {1, 2, 3, 4}; String str = intArrayToString(intArray); System.out.println("整数数组字符串: " + str); String reversedStr = reverseStringForInt(str); System.out.println("逆转后的字符串: " + reversedStr); int[] reversedArray = stringToIntArray(reversedStr); System.out.println("逆转字符串转回整数数组: " + Arrays.toString(reversedArray)); } } ``` 在上述代码中,`intArrayToString` 方法使用逗号作为分隔符将整数数组元素连接成字符串,`reverseStringForInt` 方法字符串进行逆转,`stringToIntArray` 方法根据逗号分隔符将字符串拆分为整数数组
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值