String Array to 2D String array - java

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.

Related

Java help regarding of arrays and printing out the individual lengths in the arrays

Currently, I have trouble attempting to print out the individual lengths efficiently.
String[] array = {"test", "testing", "tests"};
int arraylength = array[0].length();
System.out.println(arraylength);
Now, this does work in printing out the length however, it is inefficient and doesn't work if theoretically I don't know the length of the array.
Thanks for your input and I would appreciate if the code insisted contains "System.out.println" included so I don't have trouble figuring out which to print out.
Use this:
String[] array = {"test", "testing", "tests"};
for(String str : array) {
System.out.println(str.length());
}
If you are using Java 8 then it's a one liner :)
Arrays.asList(array).forEach(element -> System.out.println(element.length()));
What you are doing is, converting your array to a list and then running a for loop over it. Then for every element, you are printing out the length of the element.
EDIT
From one of the comment, this is even a better version of my code.
Arrays.stream(array).map(String::length).forEach(System.out::println);
Here first you convert your array to a list and then map each element to the function length of string class, then you run a foreach over it which prints out the mapped values.
String[] array = {"test", "testing", "tests"};
The length for array is:
int arraylength = array.length;
To have retrieve length for string:
for(String string: array) {
System.out.println(string.length());
}

Splitting a String array and storing in a list

There is a string[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"} which needs to be split on the basis of , and -. The values aa,dd,aa should be stored in one list whereas bb,hh in another list. I have written this code snippet:
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split(",");
for(int j=0;j<newArr.length;j++){
resultArr = newArr[j].split("-");
appList.add(resultArr[0]);
prodList.add(resultArr[1]);
rolList.add(rresultArr[2]ol);
}
Above approach could be better if we do arr[i].split in another way so that we can run only one loop but I could not achieve that so far.
I wanted to know is there any best way to achieve the requirement.
You don't need to split it using , ,since it's not part of the String but part of the String array declaration syntax,just split it with a -
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split("-");
appList.add(newArr[0]);
prodList.add(newArr[1]);
rolList.add(newArr[2]);
}

String into char on 2D array (java)

I am trying to fill a 2D char array with 5 words. Each string must be split into single characters and fill one row of the array.
String str = "hello";
char[][] words = new char[10][5];
words[][] = str.toCharArray();
My error is at the 3rd line I don't know how to split the string "hello" into chars and fill only the 1st row of the 2-dimensional array
If you want the array to fill the first row, just asign it to the first row:
words[0] = str.toCharArray();
Since this will create a new array in the array, you should change the instantiation of words to this:
char[][] words = new char[5][];
Java has a String class. Make use of it.
Very little is known of what you want with it. But it also has a List class which I'd recommend as well. For this case, I'd recommend the ArrayList implementation.
Now onto the problem at hand, how would this code look now?
List<String> words = new ArrayList<>();
words.add("hello");
words.add("hello2");
words.add("hello3");
words.add("hello4");
words.add("hello5");
for (String s : words) {
System.out.println(s);
}
For your case if you are stuck with using arrays.
String str="hello";
char[][] words = new char[5][];
words[][] = str.toCharArray();
Use something along the line of
String str = "hello";
char[][] words = new char[5][];
words[0] = str.toCharArray();
for (int i = 0; i < 5; i++) {
System.out.println(words[i]);
}
However, why invent the wheel again? There are cases however, more can be read on the subject here.
Array versus List<T>: When to use which?

type casting a String to Object[][]

I would like to convert below String to simple two dimensional array (Object[][]).
String personArray ="{{Melroy,25,India},{Jack,26,USA}}"; // nothing but a simple string with appearance of a 2D array
Can this be done in the first place?
If so what is the simplest way?
Any help any inputs will be greatly appreciated.
Starting from beginning, identify format of your data structure,
seems like your inner array have format {String, Number, String}, to find it, we will create simple regular expression \\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}
to make it work properly, you might need to add few modifications, but bellow code will work for your small case
String personArray ="{{Melroy,25,India},{Jack,26,USA}}";
Pattern pattern = Pattern.compile("\\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}");
Matcher matcher = pattern.matcher(personArray);
List<Object[]> list = new ArrayList<>();
//using list as we don't know number of final elements,
int start = 0;
while(
matcher.find(start)){
list.add(new Object[]{matcher.group(1),matcher.group(2),matcher.group(3)});
start = matcher.end();
}
//convert to array, to have required format
Object[][] array = list.toArray(new Object[0][]);
//test result
for (Object[] arr : array)
System.out.println(Arrays.toString(arr));

multiply string element per int element from two arrays Java

I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"

Categories