How to extract an array from string input? - java

Input is in this format...
String input = "3 12#45#33 94#54#23 98#59#27";
To be extracted in this array...
int[][] array = new int[3][3];

You can split the string and then iterate over the array. Which results in something like this:
String input = "3 12#45#33 94#54#23 98#59#27";
String[] strings = input.split(" ");
int size = Integer.parseInt(strings[0]);
int[][] result = new int[size][size];
for( int i = 0; i < strings.length - 1; i++ ){
String[] strings2 = strings[i + 1].split("#");
for( int j = 0; j < strings2.length; j++ ){
result[i][j] = Integer.parseInt(strings2[j]); // add the parsed int to result
}
}

Related

How can I backfill a Java string array based on two other arrays?

I have two arrays:
String[] ArrayA = {"9","1","4","2","3"};
String[] ArrayB = {"9","2","8"};
How do I get a new array like the following
String[] ArrayC = {"9","2","8","A","A"};
The logic is to create a new ArrayC of length equal to ArrayA and backfill the remaining array elements (ArrayA length minus ArrayB length = 2) difference with "A".
Read the javadoc of Arrays.
arrayC = Arrays.copyOf(arrayB, arrayA.length);
Arrays.fill(arrayC, arrayB.length, arrayA.length, "A");
You could just iterate over arrayB and copy it:
String[] arrayA = {"9","1","4","2","3"};
String[] arrayB = {"9","2","8"};
String[] arrayC = new String[arrayA.length];
// copy arrayB:
for (int i = 0; i < arrayB.length; ++i) {
arrayC[i] = arrayB[i];
}
// fill in the remainder:
for (int i = arrayB.length; i < arrayA.length; ++i) {
arrayC[i] = "A";
}
Based on the previous posted code,this is a generic method which satisfy your need, it takes 3 params , two arrays and the word to be used to be used in replacing empty elements
public static String [] fill(String [] arrayA, String[] arrayB ,String word) {
String[] toBeCopied = null ;
int size ;
if( arrayA.length > arrayB.length ) {
size = arrayA.length ;
toBeCopied = arrayB ;
} else {
size = arrayB.length ;
toBeCopied = arrayA ;
}
String[] arrayC = new String[size];
for (int i = 0; i < toBeCopied.length; ++i) {
arrayC[i] = toBeCopied[i];
}
for (int i=toBeCopied.length;i<arrayC.length ;i++ )
arrayC[i] = word;
return arrayC ;
}

a method that recieves String input and divides it into 1,2 and 3 different sections

i need a more basic method! that will just split words into 1,2,3 consecutive compartments, my output for "water" should be in terms of array string! e.g INPUT of water should produce OUTPUT like {"w","a","t","e","r","wa","at","te","er","wat","ate","ter"}
public void split(String word) {
int x=(word.length())/2;
int z=word.length();
String[] partition= new String[5];
for (int i=0; i<x; i++){
String new1=Character.toString(word.charAt(i));
String new2 = Character.toString(word.charAt(i))+Character.toString(word.charAt(i+1));
String new3 = Character.toString(word.charAt(i))+Character.toString(word.charAt(i+1))+Character.toString(word.charAt(i+2));
String new4 = removeDuplicate(Character.toString(word.charAt(z-2))+ Character.toString(word.charAt(z-1)));
String new5 = removeDuplicate(Character.toString(word.charAt(z-3))+ Character.toString(word.charAt(z-2))+ Character.toString(word.charAt(z-1)));
char result = word.charAt(2);
String[] partitions = {new1,new5,new3,new4,new2};
//partition=partitions;
//Arrays.toString((removeDuplicates(partitions)))
System.out.println(partitions);
}
//return partition;
}
Here is an example how you can do that. I hope if you are not a beginner you know about ArrayList.
String word = "water";
ArrayList<String> list = new ArrayList<String>();
for (int i = 1; i <= 3; i++) {
int limit = word.length() - i + 1;
for (int j = 0; j < limit; j++) {
list.add(word.substring(j, j+i));
}
}
System.out.println(list);
Output :
[w, a, t, e, r, wa, at, te, er, wat, ate, ter]
Try to understand it. and tell me if having any doubt.
public String[] foo(String word){
String[] consec = new String[3*word.length() - 3];
String substr;
int k = 0;
for(int i = 1; i <= 3; i++){
for(int j = 0; j <= word.length() - i; j++){
substr = word.substring(j, j+i);
consec[k] = substr;
k++;
}
}
return consec;
}

Importing input file to integer array

This is the content of my Input file:
123
I want to take this input content to a int[] Array
My code:
BufferedReader br = new BufferedReader(new FileReader("yes.txt"));
int[] Array = br.readline().toCharArray(); // Error as it has to be int array
How to solve this:
output:
Array[0]=1
Array[0]=2
Array[0]=3
Simple convert of your string to int array:
private int[] convertStringToIntArray(String str) {
int[] resultArray = new int[str.length()];
for (int i = 0; i < str.length(); i++)
resultArray[i] = Character.getNumericValue(str.charAt(i));
return resultArray;
}
Once you have your string in, it's very simple.
I would recommend using an arraylist for this, as it is easier to add new elements on the fly.
String inputNumbers = "12345";
ArrayList<Integer> numberList = new ArrayList<Integer>();
for(int i = 0; i < inputNumbers.length(); i++) {
numberList.add(Integer.valueOf(numberList.substring(i,i+1)));
}
And there you go! You now have an arraylist called numberList where you can access all of the numbers with numberList.get(0), numberList.get(1), etc.
First read the input as string then convert to int array as below
String inputString = br.readline()
int[] num = new int[inputString.length()];
for (int i = 0; i < inputString.length(); i++){
num[i] = inputString.charAt(i) - '0';
}
Another way is to convert the char array to int array
char[] list = inputString.toCharArray();
int[] num = new int[inputString.length()];
for (int i = 0; i > inputString.length(); i++){
num[i] = list[i];
}
System.out.println(Arrays.toString(num));

Convert a 1D string to a 2D array of Integers

I have a string and I want to convert it to a 2D array of integers. This is what I am doing:
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
//Putting each element into an array of strings
String stringArray[]=string1.split("~");
//Determining the number of columns for the 2D array
int countints=0;
Scanner ins = new Scanner(stringArray[0]);
while (ins.hasNext()){
countints+=1;
ins.next();
}
//converting into an array of integers
int intArray[][]=new int[stringArray.length][countints];
Here I'm stuck as how to parse each integer into the 2D array.
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String string2 = string1.replace("[","").replace("]","");
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
For a totally dynamic array:
String string1 = "[1,2,3]~[4,5,6]~[7,8,9]~";
String[] lines = string1.split("(^|~)\\[");
int[][] array = new int[lines.length][0];
Pattern pat = Pattern.compile("\\d+");
int lineIndex = 0;
for (String line : lines) {
//if the row size is dynamic
Matcher m1 = pat.matcher(line);
int rowSize = 0;
while (m1.find())
rowSize++;
array[lineIndex] = new int[rowSize];
int colIndex = 0;
Matcher m2 = pat.matcher(line);
while (m2.find()) {
array[lineIndex][colIndex++] = Integer.parseInt(m2.group());
}
lineIndex++;
}
for(int i=0; i<array.length;i++){
for(int j=0; j<array[i].length;j++){
System.out.print(array[i][j] + " ");
}
System.out.println();
}
It prints:
1 2 3
4 5 6
7 8 9
Once you have initialized the 2D array, you need to parse each element in stringArray by getting rid of trailing and leading '[', ']' bracket pairs and splitting it with "," and parse each element of the split string into Integer and put that int value to the given 2d array at correct postion.
EDIT: WORKING SOLUTION
String string1="[1,2,3]~[4,5,6]~[7,8,9]~";
String stringArray[]=string1.split("~");
int countints = stringArray[0].substring(1, stringArray[0].length()-1).split(",").length;
int intArray[][]=new int[stringArray.length][countints];
for(int i = 0; i < stringArray.length; i++)
{
String s = stringArray[i].substring(1, stringArray[i].length()-1);
String[] elementArray = s.split(",");
for(int j = 0; j < elementArray.length; j++)
{
int val = Integer.parseInt(elementArray[j]);
intArray[i][j] = val;
}
}
Here is a clean solution that works. I started working on it before I got through all of the other answers, so my apologies if it doesn't meaningfully add to what is already here:
public class SO {
public static int[][] parse(String input) {
String[] rows = input.split("~");
int[][] ints = new int[rows.length][];
int j = 0;
for(String row : rows) {
String[] cols = row.substring(1, row.length()-1).split(",");
int k = 0;
ints[j] = new int[cols.length];
for(String col : cols) {
ints[j][k++] = Integer.parseInt(col);
}
j++;
}
return ints;
}
public static void main(String[] args) {
for(int[] row : parse("[1,2,3]~[4,5,6]~[7,8,9]~")) {
for(int col : row) {
System.out.print(","+col);
}
System.out.println();
}
}
}
This produces the output:
,1,2,3
,4,5,6
,7,8,9
As for error checking you should decide upfront how you want to handle error checking, As this is written a single invalid int will throw an exception, which I think is the correct behavior. Malformed rows on the other hand might give unpredictable output (which I would say is wrong if the input has even the slightest potential to be malformed).

How to copy 2d String array?

I'm having difficulty copying string array values into a new string array.
For example:
String[][] array = new String[3][2];
array[0][0] = "hello";
array[0][1] = "1";
array[1][0] = "guys";
array[1][1] = "2";
array[2][0] = "good ";
array[2][1] = "3";
array = new String [5][2];
all the value in the first array to be copied
array[3][0] = "";
array........;
I tried this method but it keeps me giving null pointer issues whenever I want to insert a new value.
String[][] array = new String[3][2];
array[0][0] = "olo";
array[0][1] = "ada ";
array[1][0] = "apa";
array[1][1] = "dengan";
array[2][0] = "si ";
array[2][1] = "carlo";
String[][] newArray = new String[5][2];
newArray = Arrays.copyOf(array, 5);
array = new String[5][2];
array = Arrays.copyOf(newArray, 5);
array[3][0] = "lo";
array[3][1] = "gw";
array[4][0] = "end";
array[4][1] = "ennnnnd";
for (int r = 0; r < array.length; r++) {
for (int c = 0; c < array[r].length; c++) {
System.out.print(" " + array[r][c]);
}
System.out.println("");
}
How can I copy this 2d string array?
Java has a built in function called arraycopy that can do this for you without a double for loop. Much more efficient.
First of all the newer array has more elements that source array so decide what you want to do about it. Also if old array is called array call the new array by a different name say newarray.
for ( int i = 0; i < 3; ++i )
{
for( int j = 0; j < 2; ++i )
{
newarray[i][j] = array[i][j];
}
}
You can use Arrays.copyOfRange(String param, fromIndex, toIndex)

Categories