Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int array to char array

Is it possible to cast an int array to a char array? If so - how?


I'm currently working on a project where I need to create an char array containing the alphabet. My current code creats an int array (which should be converted to an char array - in one Line!):

return IntStream.range('a', 'z' + 1).toArray();

like image 292
TheRealVira Avatar asked Oct 07 '16 07:10

TheRealVira


People also ask

How do I convert an int to a char array?

One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );

How do I convert int to char?

Example 1: Java Program to Convert int to char char a = (char)num1; Here, we are using typecasting to covert an int type variable into the char type variable. To learn more, visit Java Typecasting. Note that the int values are treated as ASCII values.

How do I convert an int to a char array in Java?

By adding '0' We can also convert an integer into a character in Java by adding the character '0' to the integer data type. This is similar to typecasting. The syntax for this method is: char c = (char)(num + '0');

How do I convert an int to a char array in C++?

Using stringstream to convert int to Char Array in C++ In this method we will use the stringstream class. We will create a temporary string stream where we will store the int data, then we will return the string object with the help of str() method. In the end, we will use the c_str() method to complete the conversion.


1 Answers

Yeah, we’re missing a stream method to produce a char array. Maybe a whole CharStream class. In any case, no, you cannot cast between int[] and char[].

In the meantime, it’s getting a long line, but it works:

    return IntStream.rangeClosed('a', 'z')
            .mapToObj(c -> Character.toString((char) c))
            .collect(Collectors.joining())
            .toCharArray();

This gives a char[] containing

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
like image 196
Ole V.V. Avatar answered Sep 18 '22 21:09

Ole V.V.