How to print char array in C, like 'Arrays.ToString(array)' of Java?

I want to print char array in C like Arrays.ToString(array); of Java does. It prints what I want but puts some characters at the end. I guess it's because of the special character \0.

I declared a char array char letters[] = {'g','y','u','c','n','e'};

And tried to print: printf("\n [%s]:", letters);

The output is: [gyucneÇ_=]

Here is the Java code:

    char[] letters= {'g','y','u','c','n','e'};
    System.out.print( Arrays.toString(letters) );

The output is:

[g, y, u, c, n, e]

I wanted to have the output of Java code. I wonder if I want it to contain commas too, do I have to print the characters one by one or can I print it at once ?

And of course my priority is to remove the special character that is printed at the end of C code.

Upvotes: 0

Views: 984

Answers (2)

I declared a char array: char letters[] = {'g','y','u','c','n','e'};

But that is not a C string (since it is not NUL terminated ! ). You should have coded instead:

const char letters[] = {'g','y','u','c','n','e',(char)0};

(or use '\0' instead of (char)0 ....) or better yet:

const char letters[] = "gyucne";

and both are exactly equivalent.

Then you can code something like printf("letters are %s\n", letters); since your letters are now a C string.

NB. Please read also http://utf8everywhere.org/ & How to debug small programs - both are practically very relevant for your case. See also at least some C reference site.

Upvotes: 0

pmg
pmg

Reputation: 108988

Print each letter on its own. You do not have a string. You cannot call most functions from <string.h> or printf() or a bunch of others that expect a string.

char letters[] = {'g', 'y', 'u', 'c', 'n', 'e'}; // ATTENTION: letters is not a string!
for (int i = 0; i < sizeof letters; i++) {
    putchar(letters[i]);
}
putchar('\n'); // end with a newline

Upvotes: 1

Related Questions