📜  在Java中将字符数组转换为字符串

📅  最后修改于: 2021-05-17 17:05:27             🧑  作者: Mango

字符串定义为字符数组。字符数组和字符串之间的区别是字符串以特殊字符“ \ 0”终止。字符数组可以转换为字符串,反之亦然。在上一篇文章中,我们已经讨论了如何将字符串转换为字符数组。在本文中,我们将讨论如何将字符数组转换为字符串。

例子:

方法1:可以将给定字符传递给String构造函数。默认情况下,使用Arrays类中存在的Arrays.copyOf()方法复制字符数组的内容。

下面是上述方法的实现:

// Java program to demonstrate the
// conversion of a char[] array
// to a string
  
public class GFG {
  
    // Function to convert a character
    // array to a string using the
    // constructor
    public static String toString(char[] a)
    {
        String string = new String(a);
        return string;
    }
  
    // Driver code
    public static void main(String args[])
    {
  
        // Character array
        char s[] = { 'g', 'e', 'e', 'k',
                     's', 'f', 'o', 'r',
                     'g', 'e', 'e', 'k', 's' };
  
        // Print final output of char arr[]->string
        System.out.println(toString(s));
    }
}

输出:

geeksforgeeks

方法2:将字符数组转换为字符串的另一种方法是使用StringBuilder类。由于StringBuilder是一个可变的类,因此,其想法是遍历字符数组并将每个字符附加在字符串的末尾。最后,字符串包含字符的字符串形式。

下面是上述方法的实现:

// Java program to demonstrate the
// conversion of a char[] array
// to a string
  
public class GFG {
  
    // Function to convert a character
    // array to a string using the
    // StringBuilder class
    public static String toString(char[] a)
    {
        StringBuilder sb = new StringBuilder();
  
        //Using append() method to create a string
        for (int i = 0; i < a.length; i++) {
            sb.append(a[i]);
        }
  
        return sb.toString();
    }
  
    // Driver code
    public static void main(String args[])
    {
  
        // Defining character array
        char s[] = { 'g', 'e', 'e', 'k',
                     's', 'f', 'o', 'r',
                     'g', 'e', 'e', 'k', 's' };
  
        System.out.println(toString(s));
    }
}

输出:

geeksforgeeks

方法3:将字符数组转换为字符串的另一种方法是使用String类中存在的valueOf()方法。此方法固有地将字符数组转换为一种格式,在该格式中显示数组中存在的字符的整个值。简而言之,该数组将转换为String。

下面是上述方法的实现:

// Java program to demonstrate the
// conversion of a char[] array
// to a string
  
public class GFG {
  
    // Function to convert a character
    // array to a string using the
    // valueOf() method
    public static String toString(char[] a)
    {
        String string = String.valueOf(a);
  
        return string;
    }
  
    // Driver code
    public static void main(String args[])
    {
      
        // Defining character array
        char s[] = { 'g', 'e', 'e', 'k',
                     's', 'f', 'o', 'r',
                     'g', 'e', 'e', 'k', 's' };
  
        System.out.println(toString(s));
    }
}

输出:

geeksforgeeks