Converting string to char array in Java? - java

I have something like the below:
char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();
I get error "incompatible types, char[] cannot be converted to char". My final product I'd like something like the below:
array = {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}};
array becomes a [2][5] array in the end result. Is toCharArray() the incorrect method to use?

You need to have a double array. Something like
char[][] arr = new char[2][];
arr[0] = a.toCharArray();

You need an array of arrays. Something like this:
char[][] array = new char[5][];

You have to use toCharArray to get a char[] back; the problem is where you put it after you extract it.
Change your array variable to be a char[][], and define it as such:
char[][] array = new char[2][5];
Note that the result won't exactly be {{H},{E},{L},{L},{O}},{{W},{O},{R},{L},{D}}; it'd be more like {{H, E, L, L, O}},{{W, O, R, L ,D}}.

You need an array of arrays
char[][] arr = new char[5][];
arr[0] = a.toCharArray();

char[] array = new char[5];
String a = "HELLO";
String b = "WORLD";
array[0] = a.toCharArray();
array[1] = b.toCharArray();
What if a and b are not of the same length ? Your method and the ones proposed by others are very limited/specific and not flexible. Try this instead to make abstraction of the length of the String.
ArrayList<char[]> array = new ArrayList();
String a = "HELLO";
String b = "WORLD";
array.add(a.toCharArray());
array.add(b.toCharArray());

Related

Convert String to int[] array

how could I convert my String to int array?
my input:
String numbers = "123456";
What I'd like to reach:
Int numbers[]={1,2,3,4,5,6};
That String was splitted from String with this number.
If the above question is for Java.
String numbers = "123456";
int[] array = new int[numbers.length()];
for (int i = 0; i < numbers.length(); i++) {
array[i] = Character.getNumericValue(numbers.charAt(i));
System.out.println("\n"+array[i]);
}
Java 8 one liner would be:
int[] integers = Stream.of( numbers.split("") )
.mapToInt(Integer::valueOf)
.toArray();
I don't know what language you are working with. But I can tell you in c++.
character codes of digits start from 48(dec). You can add and remove this value for each element.
The code could roughly look like this.
int * _numbers=new int[numbers.size()];
for(int i=0;i<numbers.size();i++)
_numbers[i]=numbers[i]+48;
The most straightforward way is to create an array variable and loop through the string characters and push them into the array.
var str = "123456";
var arr = [];
for (let n of str) {
arr.push(parseInt(n))
}
console.log(arr);

String to Array (Java)

So my issue here is that I am trying to take in a String from user input, but then I need to convert that string into an array.
So as an example, the user inputted string would be "Hello", and the array (named arr) would be: arr[0]="H" arr[1] = "e" and so on. If anyone can point me in the right direction I would appreciate it a lot!
Use the standard library method:
char[] arr = str.toCharArray();
Documentation: java.lang.String.toCharArray()
There's a built in function to convert a string to a character array:
String myString = ...;
char[] chars = myString.toCharArray();
If you need each character as a stirng, you can loop over the character array and convert it:
String myString = ...;
String[] result = new String[myString.length];
char[] chars = myString.toCharArray();
for (int i = 0; i < chars.length; ++i) {
result[i] = String.valueOf(chars[i]);
}
Read javadoc:
String - toCharArray method
public char[] toCharArray()
Converts this string to a new character array.
String hello = "Hello";
String[] array = hello.split("");
You can use String.split("") like
String[] arr = str.split("");
That will give you an array arr where each substring is one character
[H, e, l, l, o]
Another option might be String.toCharArray() if a char[] is acceptable like
char[] arr = str.toCharArray();

JAVA: Populating an array then display using for loop

I'm trying to populate an array [C], then display it using a for loop.. I'm new to arrays and this is confusing the hell out of me, any advice is appreciated!
Below is my code:
public static void main(String[] args) {
int A[] = new int[5];
int B[] = new int[5];
String C[] = new String[5];
int D[] = new int[5];
C[] = {"John", "Cook", "Fred"};
for(String name: C)
System.out.println(C);
}}
You can define and populate an array in two ways. Using literals:
String c[] = {"John", "Cook", "Fred"};
for(String name : c) { // don't forget this { brace here!
System.out.println(name); // you want to print name, not c!
}
Or by setting each index element:
int d[] = new int[2];
d[0] = 2;
d[1] = 3;
for(int num: d) {
System.out.println(num);
}
(You can only use the literal when you first define the statement, so
String c[];
c = {"John", "Cook", "Fred"};
Will cause an "illegal start of expression" error.)
You want to print name instead of C.
C is the name of the array, while name is the name of the String variable. Therefore you must print name instead of C
System.out.println(name);
for(int i=0;i<=2;i++){
System.out.println(C[i]);
}
here 2 is the last index of the array C
You cannot simply print an array you have to provide an index to your item
where C[0] is john and C[1] is Cook and so on
and if you want to use a for each loop then this is how it goes
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
Try specifying at what index you want to add the element.
Example:
C[0] = "hej";
Also, print the element in the array, not the actual array. (System.out.println(name);)

Splitting the string and store it in an array

I want the following string to be stored into an array but it throws ArrayOutOfBound Exception.
public static void main(String[] args) {
// TODO Auto-generated method stub
char[] arr = {};
String str = "Hello My Name is Ivkaran";
for (int i = 0;i < str.length(); i++){
System.out.println(str.charAt(i));
arr[i] = str.charAt(i);
}
}
You've declared an array of length 0 with this line:
char[] arr = {};
To assign anything to that array, it must be initialized to some non-zero size. Here, it looks like you need it to be the same size as the string.
String str = "Hello My Name is Ivkaran";
char[] arr = new char[str.length()];
You can also just call toCharArray() on the String to get a char[] with the contents copied into it already.
char[] arr = str.toCharArray();
Arrays are not dynamic in Java. Either use an arraylist or create the array with a dimention as:
char[] arr = new char[str.length()]
Also move this line below the
String str = "Hello My Name is Ivkaran";
Then continue as originally.
Just do this:
String str = "Hello My Name is Ivkaran";
char[] arr = str.toCharArray();

Converting String to "Character" array in Java

I want to convert a String to an array of objects of Character class but I am unable to perform the conversion. I know that I can convert a String to an array of primitive datatype type "char" with the toCharArray() method but it doesn't help in converting a String to an array of objects of Character type.
How would I go about doing so?
Use this:
String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
One liner with java-8:
String str = "testString";
//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray =
str.chars().mapToObj(c -> (char)c).toArray(Character[]::new);
What it does is:
get an IntStream of the characters (you may want to also look at codePoints())
map each 'character' value to Character (you need to cast to actually say that its really a char, and then Java will box it automatically to Character)
get the resulting array by calling toArray()
Why not write a little method yourself
public Character[] toCharacterArray( String s ) {
if ( s == null ) {
return null;
}
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++) {
/*
Character(char) is deprecated since Java SE 9 & JDK 9
Link: https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html
array[i] = new Character(s.charAt(i));
*/
array[i] = s.charAt(i);
}
return array;
}
Converting String to Character Array and then Converting Character array back to String
//Givent String
String given = "asdcbsdcagfsdbgdfanfghbsfdab";
//Converting String to Character Array(It's an inbuild method of a String)
char[] characterArray = given.toCharArray();
//returns = [a, s, d, c, b, s, d, c, a, g, f, s, d, b, g, d, f, a, n, f, g, h, b, s, f, d, a, b]
//ONE WAY : Converting back Character array to String
int length = Arrays.toString(characterArray).replaceAll("[, ]","").length();
//First Way to get the string back
Arrays.toString(characterArray).replaceAll("[, ]","").substring(1,length-1)
//returns asdcbsdcagfsdbgdfanfghbsfdab
or
// Second way to get the string back
Arrays.toString(characterArray).replaceAll("[, ]","").replace("[","").replace("]",""))
//returns asdcbsdcagfsdbgdfanfghbsfdab
//Second WAY : Converting back Character array to String
String.valueOf(characterArray);
//Third WAY : Converting back Character array to String
Arrays.stream(characterArray)
.mapToObj(i -> (char)i)
.collect(Collectors.joining());
Converting string to Character Array
Character[] charObjectArray =
givenString.chars().
mapToObj(c -> (char)c).
toArray(Character[]::new);
Converting char array to Character Array
String givenString = "MyNameIsArpan";
char[] givenchararray = givenString.toCharArray();
String.valueOf(givenchararray).chars().mapToObj(c ->
(char)c).toArray(Character[]::new);
benefits of Converting char Array to Character Array you can use the Arrays.stream funtion to get the sub array
String subStringFromCharacterArray =
Arrays.stream(charObjectArray,2,6).
map(String::valueOf).
collect(Collectors.joining());
String#toCharArray returns an array of char, what you have is an array of Character. In most cases it doesn't matter if you use char or Character as there is autoboxing. The problem in your case is that arrays are not autoboxed, I suggest you use an array of char (char[]).
You have to write your own method in this case. Use a loop and get each character using charAt(i) and set it to your Character[] array using arrayname[i] = string.charAt[i].
I hope the code below will help you.
String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
System.out.println("Data at ["+i+"]="+arr[i]);
}
It's working and the output is:
Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]=
Data at [8]=t
Data at [9]=o
Data at [10]=
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]=
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g
another way to do it.
String str="I am a good boy";
char[] chars=str.toCharArray();
Character[] characters=new Character[chars.length];
for (int i = 0; i < chars.length; i++) {
characters[i]=chars[i];
System.out.println(chars[i]);
}
This method take String as a argument and return the Character Array
/**
* #param sourceString
* :String as argument
* #return CharcterArray
*/
public static Character[] toCharacterArray(String sourceString) {
char[] charArrays = new char[sourceString.length()];
charArrays = sourceString.toCharArray();
Character[] characterArray = new Character[charArrays.length];
for (int i = 0; i < charArrays.length; i++) {
characterArray[i] = charArrays[i];
}
return characterArray;
}
if you are working with JTextField then it can be helpfull..
public JTextField display;
String number=e.getActionCommand();
display.setText(display.getText()+number);
ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
System.out.println("in array a1= "+ch[i]);
chaining is always best :D
String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());
If you don't want to rely on third party API's, here is a working code for JDK7 or below. I am not instantiating temporary Character Objects as done by other solutions above. foreach loops are more readable, see yourself :)
public static Character[] convertStringToCharacterArray(String str) {
if (str == null || str.isEmpty()) {
return null;
}
char[] c = str.toCharArray();
final int len = c.length;
int counter = 0;
final Character[] result = new Character[len];
while (len > counter) {
for (char ch : c) {
result[counter++] = ch;
}
}
return result;
}
I used the StringReader class in java.io. One of it's functions read(char[] cbuf) reads a string's contents into an array.
String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);
try {
read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < str.length(); i++) {
System.out.println("array["+i+"] = "+array[i]);
}
Running this gives you the output:
array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o
String[] arr = { "abc", "cba", "dac", "cda" };
Map<Character, Integer> map = new HashMap<>();
String string = new String();
for (String a : arr) {
string = string.concat(a);
}
System.out.println(string);
for (int i = 0; i < string.length(); i++) {
if (map.containsKey(string.charAt(i))) {
map.put(string.charAt(i), map.get(string.charAt(i)) + 1);
} else {
map.put(string.charAt(i), 1);
}
}
System.out.println(map);
//out put {a=4, b=2, c=4, d=2}

Categories