I start with an array of strings formatted useful.useless
. I need to trim out the .useless
part, and then put the useful
part in a 2D char
array.
I see a way that involves creating a second string array containing only the useful
part, and then converting that to a 2D char array, but there is probably a more effective way.
However, I don't know how to convert string array to 2D char array
public static void main (String[]args){
// this here is just to create an array so the example runs
String in = "useful1.useless1,useful2.useless2,useful3.useless3,";
String[] strArray = null;
strArray = in.split(",");
/*the array of strings is thus
[useful1.useless1, useful2.useless2, useful3.useless3]
*/
char [][] charArray = new char [strArray.length][];
/* trim from the . so only useful part remains
then put in 2d char array, which should look like
[u,s,e,f,u,l,1]
[u,s,e,f,u,l,2]
[u,s,e,f,u,l,3]
the array will be a ragged array
*/
}
CodePudding user response:
You need to populate charArray
at each index, with the array of characters of the desired substring of strArray
at the corresponding index. You can do it as shown below:
for (int i = 0; i < strArray.length; i )
charArray[i] = strArray[i].substring(0, strArray[i].indexOf('.')).toCharArray();
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// this here is just to create an array so the example runs
String in = "useful1.useless1,useful2.useless2,useful3.useless3,";
String[] strArray = in.split(",");
/*
* the array of strings is thus [useful1.useless1, useful2.useless2,
* useful3.useless3]
*/
char[][] charArray = new char[strArray.length][];
for (int i = 0; i < strArray.length; i )
charArray[i] = strArray[i].substring(0, strArray[i].indexOf('.')).toCharArray();
// Display
for (char[] row : charArray)
System.out.println(Arrays.toString(row));
}
}
Output:
[u, s, e, f, u, l, 1]
[u, s, e, f, u, l, 2]
[u, s, e, f, u, l, 3]
CodePudding user response:
Stream the strings:
- use regex to “remove” the useless part
- convert the ”useful”
String
to achar[]
- collect all
char[]
into achar[][]
Voila:
char[][] usefulChars = Arrays.stream(strArray)
.map(s -> s.replaceAll("\\..*", ""))
.map(String::toCharArray)
.toArray(char[][]::new);
See live demo.