I have a weird situation, am working on a Data base project that only gives me a string [] s = ["A","B","C","D"] and I wanted to change from string array to Char Array since it's a char but i dunno what function to use to convert the entire array to char with one line of code.
char ch = [ 'A', 'B', 'C'] --> this is what am looking to get
My plan B is to loop the entire string and convert to char one by one. but am avoiding that one.
any help I will highly appreciate
this might help you.
Would be better if we could use Stream<char>, but, this does not work, so, we need to use the wrapper class.
Since you want the first index, you can use 0.
String.charAt(index) returns a char primitive, so, it will use less memory than a String.substring(...) that returns a new String.
final String[] array = {"A", "B", "C", "D"};
final Character [] char_array = Arrays.stream(array)
.map(s -> s.charAt(0))
.toArray(Character[]::new);
for(char a: char_array) {
System.out.println(a);
}
You can use streams, this will return a char [] array.
Arrays.stream(S).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray();
Full code
String [] S = { "A", "B", "C"} ;
char [] ch =Arrays.stream(S).map(s -> s.substring(0,1))
.collect(Collectors.joining()).toCharArray();
for(int i=0;i<ch.length;i++){
System.out.println(ch[i]);
}
For better use, I suggest making a method that implements this stream and returns a char []
public char [] convertToChar(String [] yourArray){
return Arrays.stream(youArray).map(s -> s.substring(0,1)).collect(Collectors.joining()).toCharArray();
}
Related
I have a String of the following kind in Java. The idea is that the string will contain a list of numbers followed by'Y-' or 'N-'. They may be of any length. I need to extract the list of numbers into two, separately.
String str = "Y-1,2,3,4N-5,6,7,8"
//Other examples: "Y-1N-3,6,5" or "Y-1,2,9,18N-36"
I need to break it down into the following arrays:
arr1[] = {1,2,3,4}
arr2[] = {5,6,7,8}
How do I do it?
First split the string into the two arrays string parts
String str = "Y-1,2,3,4N-5,6,7,8";
String str1 = str.substring(2, str.indexOf("N-")); // "1,2,3,4"
String str2 = str.substring(str.indexOf("N-") + 2); // "5,6,7,8"
Then convert the array of strings to an array of ints using the Integer.parseInt(), simple java-8 solution with streams:
int[] array1 = Arrays.stream(str1.split(",")).mapToInt(Integer::parseInt).toArray();
int[] array2 = Arrays.stream(str2.split(",")).mapToInt(Integer::parseInt).toArray();
If you are in a version of java without streams, you need to use a simple for loop instead of the Arrays.stream()
Can anyone help me and tell how to convert a char array to a list and vice versa.
I am trying to write a program in which users enters a string (e.g "Mike is good") and in the output, each whitespace is replaced by "%20" (I.e "Mike%20is%20good"). Although this can be done in many ways but since insertion and deletion take O(1) time in linked list I thought of trying it with a linked list. I am looking for someway of converting a char array to a list, updating the list and then converting it back.
public class apples
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
StringBuffer sb = new StringBuffer(input.nextLine());
String s = sb.toString();
char[] c = s.toCharArray();
//LinkedList<char> l = new LinkedList<char>(Arrays.asList(c));
/* giving error "Syntax error on token " char",
Dimensions expected after this token"*/
}
}
So in this program the user is entering the string, which I am storing in a StringBuffer, which I am first converting to a string and then to a char array, but I am not able to get a list l from s.
I would be very grateful if someone can please tell the correct way to convert char array to a list and also vice versa.
In Java 8 and above, you can use the String's method chars():
myString.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
And if you need to convert char[] to List<Character>, you might create a String from it first and then apply the above solution. Though it won't be very readable and pretty, it will be quite short.
Because char is primitive type, standard Arrays.asList(char[]) won't work. It will produce List<char[]> in place of List<Character> ... so what's left is to iterate over array, and fill new list with the data from that array:
public static void main(String[] args) {
String s = "asdasdasda";
char[] chars = s.toCharArray();
// List<Character> list = Arrays.asList(chars); // this does not compile,
List<char[]> asList = Arrays.asList(chars); // because this DOES compile.
List<Character> listC = new ArrayList<Character>();
for (char c : chars) {
listC.add(c);
}
}
And this is how you convert List back to array:
Character[] array = listC.toArray(new Character[listC.size()]);
Funny thing is why List<char[]> asList = Arrays.asList(chars); does what it does: asList can take array or vararg. In this case char [] chars is considered as single valued vararg of char[]! So you can also write something like
List<char[]> asList = Arrays.asList(chars, new char[1]); :)
Another way than using a loop would be to use Guava's Chars.asList() method. Then the code to convert a String to a LinkedList of Character is just:
LinkedList<Character> characterList = new LinkedList<Character>(Chars.asList(string.toCharArray()));
or, in a more Guava way:
LinkedList<Character> characterList = Lists.newLinkedList(Chars.asList(string.toCharArray()));
The Guava library contains a lot of good stuff, so it's worth including it in your project.
Now I will post this answer as a another option for all those developers that are not allowed to use any lib but ONLY the Power of java 8:)
char[] myCharArray = { 'H', 'e', 'l', 'l', 'o', '-', 'X', 'o', 'c', 'e' };
Stream<Character> myStreamOfCharacters = IntStream
.range(0, myCharArray.length)
.mapToObj(i -> myCharArray[i]);
List<Character> myListOfCharacters = myStreamOfCharacters.collect(Collectors.toList());
myListOfCharacters.forEach(System.out::println);
You cannot use generics in java with primitive types, why?
If you really want to convert to List and back to array then dantuch's approach is the correct one.
But if you just want to do the replacement there are methods out there (namely java.lang.String's replaceAll) that can do it for you
private static String replaceWhitespaces(String string, String replacement) {
return string != null ? string.replaceAll("\\s", replacement) : null;
}
You can use it like this:
StringBuffer s = new StringBuffer("Mike is good");
System.out.println(replaceWhitespaces(s.toString(), "%20"));
Output:
Mike%20is%20good
All Operations can be done in java 8 or above:
To the Character array from a Given String
char[] characterArray = myString.toCharArray();
To get the Character List from given String
ArrayList<Character> characterList
= (ArrayList<Character>) myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
To get the characters set from given String
Note: sets only stores unique value. so if you want to get only unique characters from a string, this can be used.
HashSet<Character> abc =
(HashSet<Character>) given.chars().mapToObj(c -> (char)c).collect(Collectors.toSet());
To get Characters in a specific range from given String :
To get the character whose unicode value is greater than 118.
https://unicode-table.com/en/#basic-latin
ASCII Code value for characters
* a-z - 97 - 122
* A-Z - 65 - 90
given.chars().filter(a -> a > 118).mapToObj(c -> (char)c).forEach(a -> System.out.println(a));
It will return the characters: w,x, v, z
you ascii values in the filter you can play with characters. you can do operations on character in filter and then you can collect them in list or set as per you need
I guess the simplest way to do this would be by simply iterating over the char array and adding each element to the ArrayList of Characters, in the following manner:
public ArrayList<Character> wordToList () {
char[] brokenStr = "testing".toCharArray();
ArrayList<Character> result = new ArrayList<Character>();
for (char ch : brokenStr) {
result.add(ch);
}
return result;
}
List strList = Stream.of( s.toCharArray() ).map( String::valueOf ).collect( Collectors.toList() );
Try Java Streams.
List<Character> list = s.chars().mapToObj( c -> (char)c).collect(Collectors.toList());
Generic arguments cannot be primitive type.
if you really want to convert char[] to List, you can use .chars() to make your string turns into IntStream, but you need to convert your char[] into String first
List<Character> charlist = String.copyValueOf(arrChr)
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toList());
Try this solution
List<Character> characterList = String.valueOf(chars).chars().mapToObj(i -> (char) i).toList();
I have a String Array, map[] which looks like...
"####"
"#GB#"
"#BB#"
"####"
So map[1] = "#GB#"
How do I turn this into a 2D array so that newMap[1][1] would give me "G"?
Thanks a lot.
If you really need it, you can use String.toCharArray on each element array to convert them into an array.
String[] origArr = new String[10];
char[][] charArr = new char[10][];
for(int i = 0; i< origArr.length;i++)
charArr[i] = origArr[i].toCharArray();
If you want to break it up into String[] instead, you could use (thanks Pshemo)
String[] abc = "abc".split("(?!^)"); //-> ["a", "b", "c"]
This won't be dynamic. It will take O(n) + m to get to a character of a string. A much faster and dynamic approach would be a Hashmap where the key is the String and the value is a char array. Kind of unnecessarily complex but you get the seeking and individual letter charAts without having to go through the cumbersome process of resizing a primitive array.
I tried to make a program that separates characters.
The question is:
"Create a char array and use an array initializer to initialize the array with the characters in the string 'Hi there'. Display the contents of the array using a for-statement. Separate each character in the array with a space".
The program I made:
String ini = "Hi there";
char[] array = new char[ini.length()];
for(int count=0;count<array.length;count++) {
System.out.print(" "+array[count]);
}
What should I do to fix this problem?
Here's how you convert a String to a char array:
String str = "someString";
char[] charArray = str.toCharArray();
I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.
Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt() in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
char array[] = new String("Hi there").toCharArray();
for(char c : array)
System.out.print(c + " ");
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
Instead of above way u can achieve the solution simply by following method..
public static void main(String args[]) {
String ini = "Hi there";
for (int i = 0; i < ini.length(); i++) {
System.out.print(" " + ini.charAt(i));
}
}
You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.
Another easy way is that you use string literal and convert it to charArray in declaration itself.
Something like this -
char array[] = "Hi there".toCharArray();
//Print with white spaces
for(char c : array)
System.out.print(c + " ");
e.g.:
If the number is 234, I would like the result to be List<String> containing 2,3,4 (3 elements)
If the number is 8763, I would like the result to be List<String> containing 8,7,6,3 (4 elements)
Does commons-math already have such a function?
Convert the number to a String (123 becomes "123"). Use Integer.toString.
Convert the string to a char array ("123" becomes {'1', '2', '3'}). Use String.toCharArray.
Construct a new, empty Vector<String> (or some other List type).
Convert each char in the char array to a String and push it onto the Vector ({'1', '2', '3'} becomes a Vector with "1", "2" and "3"). Use a for loop, Character.toString and List.add.
Edit: You can't use the Vector constructor; have to do it manually.
int num = 123;
char[] chars = Integer.toString(num).toCharArray();
List<String> parts = new Vector<String>();
for (char c : chars)
{
parts.add(Character.toString(c));
}
There isn't an easier way to do this because it really isn't a very obvious or common thing to want to do. For one thing, why do you need a List of Strings? Can you just have a list of Characters? That would eliminate step 3. Secondly, does it have to be a List or can it just be an array? That would eliminate step 4.
You can use the built in java.util.Arrays.asList:
int num = 234;
List<String> parts = Arrays.asList(String.valueOf(num).split("\\B"));
Step by step this:
Converts num to a String using String.valueOf(num)
Splits the String by non-word boundaries, in this case, every letter boundary except the start and the finish, using .split("\\B") (this returns a String[])
Converts the String[] to a List<String> using Arrays.asList(T...)
Arrays.asList( String.valueOf(number).toCharArray() )
Try this:
Arrays.asList(String.valueOf(1234).split("(?!^)"))
It will create list of Strings:
["1", "2", "3", "4"]
This seems like homework.
Consider using % and / to get each digit instead of converting the entire number to a String