java使用字符串类构造函数将char数组转换为字符串

String 类是java.lang包中的一个 java 类。字符数组可以传递给 String 类的构造函数,后者将这些字符分配到新的 String 中。使用该类的构造函数,您将获得字符序列,即来自char[] 数组的字符串。

句法:

public String(char[] value)

这里的 value 是字符数组。

示例: 在此示例中,我们将使用 String 类的构造函数将 char 数组转换为 java 中的字符串。我们将在创建类的对象时将 char 数组传递给 String 类的构造函数。

注意:构造函数是一种特殊的方法,与它所属的类同名。当一个类的对象被实例化时,它的构造函数被调用。因此,在创建 String 类的对象时,默认会调用构造函数,因此无需显式调用它。

//Java program to convert character array to string 
//using String Class Constructor.
class DemoCharArrayToString{
    public static void main(String args[])
    {
        //character array
        char ch_arr[] = {'H','e','l','l','o',' ','W','o','r','l','d','!'};
        
        //Creating object of string class 
        //and passing character array to its constructor
        String str1 = new String(ch_arr);
        
        //Printing output in form of string
        System.out.println("String: "+ str1);
    }
}

输出:

String: Hello World!

在上面的示例中,char 数组ch_arr[]在实例化类的对象时作为参数传递给 String 类的构造函数。构造函数将字符数组转换为字符串,我们得到所需的输出。

java使用字符串类构造函数将char数组转换为字符串

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注