Converting String to "Character" array in Java - 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}

Related

How to return a string without the first character using an array

How do I return a string e.g. H4321 but return the numbers only, not the H. I need to use an array. So far I have:
char [] numbers = new char[5];
return numbers;
Assuming I need a line between those two. String is called value
You can use substring method on String object.
Like this:
String newValue = value.substring(1);
and then call: char[] charArray = newValue.toCharArray();
Another solution - it copies old array without first element. :
char[] newNumbers = Arrays.copyOfRange(numbers, 1, numbers.length);
Use the code bellow:
public String getNumber(){
char [] numbers = new char[5];
numbers = new String("H4321").toCharArray();
String result = "";
for(int i = 0; i < numbers.length ; i++){
if(Character.isDigit(numbers[i])){
result += numbers[i];
}
}
return result;
}

How to convert ArrayList of Strings to char array

The following code converts ArrayList<String> to char[] and print output which appears as [back, pack]. Here, the char[] includes ',' and ' '. Is there a way to do it in another way to get rid of comma and space?
ArrayList<String> list = new ArrayList<String>();
list.add("back");
list.add("pack");
char[] chars = list.toString().toCharArray();
for (char i : chars){
System.out.print(i);
}
Just replace the this line
char[] chars = list.toString().toCharArray();
with below two lines
String str=list.toString().replaceAll(",", "");
char[] chars = str.substring(1, str.length()-1).replaceAll(" ", "").toCharArray();
You can do it by joining the Strings in your ArrayList<String> and then getting char[] from the result:
char[] chars = list.stream().collect(Collectors.joining()).toCharArray();
Here .stream.collect(Collectors.joining()) part is Java 8 Stream way to join a sequence of Strings into one. See: Collectors.joining() docs.
If you want any delimiter between the parts in the result, use Collectors.joining(delimiter) instead.
There's also an overload which adds prefix and suffix to the result, for example, if you want [ and ] in it, use Collectors.joining("", "[", "]").
String to charArray in Java Code:
ArrayList<String> list = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
list.add( "back" );
list.add( "pack" );
for ( String string : list )
{
for ( char c : string.toCharArray() )
{
chars.add( c );
}
}
System.out.println( chars );
Your toString method on list is what is adding the comma and space, it's a String representation of your list. As list is a collection of Strings you don't need to call toString on it, just iterate through the collection converting each String into an array of chars using toCharArray (I assume you will probably want to add all the chars of all the Strings together).
Just an example how should you resolved large list to array copy. Beware number of characters must be less then Integer.MAX. This code is just an example how it could be done. There are plenty of checks that one must implement it to make that code works properly.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class WrappedList {
//Or replace with some better counter
int totalCharCount = 0;
final List<String> list;
public WrappedList() {
this(new ArrayList<String>());
}
public WrappedList(final List<String> list) {
this.list = list;
}
public void add(final String toAdd) {
if(toAdd != null) {
totalCharCount += toAdd.length();
this.list.add(toAdd);
}
}
public List<String> getList() {
return Collections.unmodifiableList(list);
}
public char[] toCharArray() {
return this.toCharArray(this.totalCharCount);
}
public char[] toCharArray(final int charCountToCopy) {
final char[] product = new char[charCountToCopy];
int buffered = 0;
for (String string : list) {
char[] charArray = string.toCharArray();
System.arraycopy(charArray, 0, product, buffered, charArray.length);
buffered += charArray.length;
}
return product;
}
//Utility method could be used also as stand-alone class
public char[] toCharArray(final List<String> all) {
int size = all.size();
char[][] cpy = new char[size][];
for (int i = 0; i < all.size(); i++) {
cpy[i] = all.get(i).toCharArray();
}
int total = 0;
for (char[] cs : cpy) {
total += cs.length;
}
return this.toCharArray(total);
}
public static void main(String[] args) {
//Add String iteratively
WrappedList wrappedList = new WrappedList();
wrappedList.add("back");
wrappedList.add("pack");
wrappedList.add("back1");
wrappedList.add("pack1");
final char[] charArray = wrappedList.toCharArray();
System.out.println("Your char array:");
for (char c : charArray) {
System.out.println(c);
}
//Utility method one time for all, should by used in stand-alone Utility class
System.out.println("As util method");
System.out.println(wrappedList.toCharArray(wrappedList.getList()));
}
}
See also: system-arraycopy-than-a-for-loop-for-copying-arrays

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();

Convert String array to Char array

I'm extremely stuck here.
How would I convert a String array to a Char array?
I know of:
char[] myCharArray = myStringArray.toCharArray();
But obviously that doesn't work.
How would I do this?
You need to use a 2d/jagged array.
char[][] char2dArray = new char[myStringArray.length()][];
for ( int i=0; i < myStringArray.length(); i++) {
char2dArray[i] = myStringArray[i].toCharArray();
}
Here's one way to grab all the chars from all the strings in a single char array, if that's what you meant with the question:
String[] strArray = {"ab", "cd", "ef"};
int count = 0;
for (String str : strArray) {
count += str.length();
}
char[] charArray = new char[count];
int i = 0;
for (String str : strArray) {
for (char c : str.toCharArray()) {
charArray[i++] = c;
}
}
System.out.println(Arrays.toString(charArray));
=> [a, b, c, d, e, f]
You need to iterate through your String array converting every string in the string array to a char and then add that new char to your char array.
Assuming that a myStringArray is an array of Strings you would have to first iterate through this array extracting each individual String before converting the String to an array of chars.
for example
for (String str : myStringArray) {
{
char[] myCharArray = myStringArray.toCharArray();
// do something with myCharArray
}

Remove array duplicates

I'm trying to remove duplicates from the array, but it is not working.
Am I missing something ?
Code :-
class RemoveStringDuplicates {
public static char[] removeDups(char[] str) {
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
str[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return str;
}
public static void main(String[] args) {
char str[] = "test string".toCharArray();
System.out.println(removeDups(str));
}
}
Output :-
tes ringing //ing should not have been repeated!
Instead of assigning the characters into the same array, you should use a new array. Because, after removing the duplicates, the trailing elements are not being removed, and thus are printed.
So, if you use a new array, the trailing elements would be null characters.
So, just create an new array:
char[] unique = new char[str.length];
And then change the assignment:
str[res_ind] = str[ip_ind];
to:
unique[res_ind] = str[ip_ind];
Also, you can consider using an ArrayList instead of an array. That way you won't have to maintain a boolean array for each character, which is quite too much. You are loosing some not-needed extra space. With an ArrayList, you can use the contains method to check for the characters already added.
Well, you can also avoid doing all those counting stuffs manually, by using a Set, which automatically removes duplicates for you. But most implementation does not maintain insertion order. For that you can use LinkedHashSet.
The specific problem has already found a solution, but if you are not restricited to using your own method and can use the java libraries, I would suggest something like this:
public class RemoveDuplicates {
// Note must wrap primitives for generics
// Generic array creation not supported by java, gotta return a list
public static <T> List<T> removeDuplicatesFromArray(T[] array) {
Set<T> set = new LinkedHashSet<>(Arrays.asList(array));
return new ArrayList<>(set);
}
public static void main(String[] args) {
String s = "Helloo I am a string with duplicates";
Character[] c = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
c[i] = s.charAt(i);
}
List<Character> noDuplicates = removeDuplicatesFromArray(c);
Character[] noDuplicatesArray = new Character[noDuplicates.size()];
noDuplicates.toArray(noDuplicatesArray);
System.out.println("List:");
System.out.println(noDuplicates);
System.out.println("\nArray:");
System.out.println(Arrays.toString(noDuplicatesArray));
}
}
Out:
List:
[H, e, l, o, , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]
Array:
[H, e, l, o, , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]
The linkedhashset retains ordering, which might be especially important for things like characterarrays.
Try This:
public static char[] removeDups(char[] str) {
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
char a[] = new char[str.length];
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
a[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return a;
}
You basically are updating the str variable in the loop. Updating it and again looping on the updated array.
I believe the problem is caused by the fact that you are iterating over str while you are modifying it (by the line str[res_ind] = str[ip_ind]). If you copy the result to another array, it works:
class RemoveStringDuplicates {
public static char[] removeDups(char[] str) {
char result[] = new char[str.length];
boolean bin_hash[] = new boolean[256];
int ip_ind = 0, res_ind = 0;
char temp;
while (ip_ind < str.length) {
temp = str[ip_ind];
if (bin_hash[temp] == false) {
bin_hash[temp] = true;
result[res_ind] = str[ip_ind];
res_ind++;
}
ip_ind++;
}
return result;
}
public static void main(String[] args) {
char str[] = "test string".toCharArray();
System.out.println(removeDups(str));
}
}
All the other answers seem to be correct. The "ing" that you see at the end of the result is actually untouched characters already in the array.
As an alternative solution (if you want to conserve memory), you can loop over the last part of the array to delete the characters at the end because you already know they are duplicate.
//C# code, I think you just need to change str.Length here to str.length
for (int delChars = res_ind; delChars < str.Length; delChars++)
{
str[delChars] = '\0';
}
You are totally abusing the Java language with your code. The data structure classes in the standard libraries are the main point of using Java. Use them.
The correct way to code something to do what you want is here:
class RemoveStringDuplicates {
public static String removeDups(CharSequence str) {
StringBuilder b = new StringBuilder(str);
HashSet<Character> s = new HashSet<Character>();
for(int idx = 0; idx < b.size(); idx++)
if(mySet.contains(b.charAt(idx)))
b.deleteCharAt(idx--);
else
s.add(ch);
return b.toString();
}
public static void main(String[] args) {
System.out.println(removeDups(str));
}
}
There are probably even better ways of doing it, too. Don't go avoiding Java's data structures.
If you are writing code that is performance-sensitive enough that you have to use primitive code like that in your question, you should be using a different language, like C.

Categories