How to init char array using char literals?

2019-04-18 07:09发布

The following statement doesn't work in Java, but works in C:

char c[] = "abcdefghijklmn";

What's wrong?

Does the char array can only be initialized as following?

char c[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'};

标签: java char
5条回答
ら.Afraid
2楼-- · 2019-04-18 07:53

If you don't want to use String toCharArray(), then yes, a char array must be initialized like any other array- char[] c = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'};

查看更多
我命由我不由天
3楼-- · 2019-04-18 07:57

Try this:

String a = "abcdefghijklmn";   
char[] c = a.toCharArray();
查看更多
祖国的老花朵
4楼-- · 2019-04-18 07:59

You can initialize it from a String:

char[] c = "abcdefghijklmn".toCharArray();

However, if what you need is a string, you should simply use a string:

String s = "abcdefghijklmn";
查看更多
做个烂人
5楼-- · 2019-04-18 07:59

The literal "abcdefghijklmn" is a String object in Java. You can quickly convert this into a char array by using the String toCharArray() method.

Try this:

char[] c = "abcdefghijklmn".toCharArray();
查看更多
虎瘦雄心在
6楼-- · 2019-04-18 08:00

You could use

char c[] = "abcdefghijklmn".toCharArray();

if you don't mind creating an unnecessary String.

Unlike in C, Strings are objects, and not just arrays of characters.

That said, it's quite rare to use char arrays directly. Are you sure you don't want a String instead?

查看更多
登录 后发表回答