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)
Related
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
}
}
I have the array
String[] test_=new String[] {"a b c d", "f g h i","j k l s gf"};
Now i want to create another array that has the elements
{"b d", "g i","k s"}
how can I do this?
I've managed to separate the array into rows using
String split_test[] = null;
for (int j = 0 ; j <= 2 ; j++) {
split_test=test_[j].split("\\s+");
System.out.println(Arrays.toString(split_test));
}
But now I want to separate each of those rows, I tried the solution of
How to Fill a 2d array with a 1d array? Combined with something like this split_test=test_[j].split("\s+"), but I haven't been able to solve it.
Also If I do what they say I have to make the array split_test have a number of specific columns, but what I want is the size of the columns of split_test depend of the array test_. For example in case I want to have an array with the elements {"b d", "g i", "k s gf"}
String[][] split_test = new String[3][2];
for(int row = 0; row < split_test.length; row++) {
for(int col = 0; col < split_test[row].length; col++) {
split_test[row][col] = test_[row];/*I still don't understand how to use the split within the for*/
System.out.println(split_test[row][col]);
}
}
Is there a simpler and more efficient way of doing this?
Thanks
Here is another one.
You can use the substring method of String class.
Or use indexes of the array returned by the split method.
String output[] = new String[test_.length];
String split_test[] = null;
for (int j = 0; j < test_.length(); j++) {
split_test = test_[j].split("\\s+");
// use direct index
// output2[j] = split_test[1] + " " + split_test[3];
// or based on length
output[j] = split_test[1] + " " + split_test[split_test.length - 2];
}
System.out.println(Arrays.toString(output));
Output:
b d
g i
k s
I have used a different approach that works as well. I noticed you only take the uneven indexes, hence my modulo approach:
String[] array = new String[] {"a b c d", "f g h i","j k l s gf"};
String[] result = new String[array.length];
for(int i = 0; i < array.length; i++) {
String subresult = "";
String[] array2 = array[i].split(" ");
for(int j = 0; j < array2.length; j++) {
if(j % 2 == 1)
subresult += array2[j] +" ";
}
result[i] = subresult.trim();
}
You should use a 2 dimentional array, you can create one by doing:
String[][] input=new String[][] {{"a","b","c","d"}, {"f","g","h","i"},{"j","k","l","s"}};
You can then do something like this to retrieve {{"b","d"}, {"g","i"},{"k","s"}}:
String[][] output = new String[input.length][2];
for(int i = 0; i<input.length; i++)
{
output[i] = new String[]{input[i][1],input[i][3]};
}
System.out.println(Arrays.deepToString(output));
So the idea is for a given set of strings in an array, I want to combine them to create one string.
for example:
array[0] = "abcde";
array[1] = "bcfgp";
array[2] = "fbcns";
array[3] = "fbdrq";
I want to join them thus getting the first of each letter from the array.
Which I done fine with this code:
String[] array = new String[4];
array[0] = "abcde";
array[1] = "bcfgp";
array[2] = "fbcns";
array[3] = "fbdrq";
int wordLength = array[0].length();
StringBuilder b = new StringBuilder();
// check through letter in each word
for (int i = 0; i < wordLength; i++) {
char[] charArray = new char[wordLength];
// checks each word in the array
for (int j = 0; j < 4; j++) {
char ch = array[j].charAt(i);
b.append(ch);
}
}
So this code creates the string "abffbcbbcfcddgnrepsq" which is fine.
What I would like is to remove duplicates at a position of i. so for the example used:
i=01234
array[0] = "abcde";
array[1] = "bcfgp";
array[2] = "fbcns";
array[3] = "fbdrq";
so you can see that when i=0, there is a duplicate of f so rather than adding two f's to the string, how would I add just one?
i=1 There are 3 b's so i'd only add one to the string and the c
i=2 Only add 1 c to the string and the d and d..
you get the picture, the end output would be:
"abfbccfddgnrepsq"
Set can be used to identify the duplicate as follow:
StringBuilder b = new StringBuilder();
// check through letter in each word
Set<Character>st = new HashSet<>();
for (int i = 0; i < wordLength; i++) {
st.clear();
char[] charArray = new char[wordLength];
// checks each word in the array
for (int j = 0; j < 4; j++) {
char ch = array[j].charAt(i);
if(st.add(ch))
b.append(ch);
}
}
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));
For this project, I'm given an array of strings and an array of ints. int[1] is the ranking for string[1]. I need to sort the int array in order from 1 to n using mergesort, which I've done below. But I also need to switch the positions of the string array when the int array gets moved so they are both sorted, if that makes sense? I can't figure out what's wrong with my coding or even if my idea will actually work, but I keep getting an array index out of bounds error on stringSorted[k] = stringRight[j] and I can't figure out if there's a way to fix this. Essentially, when an int was added to the sortedInt array, I also added that element to the sorted String array. Thank you for any help, and let me know if something doesn't make sense
private static int sortAndCount(int intToSort[]){
int inversionsLeft;
int inversionsRight;
int inversionsMerged;
if(intToSort.length == 1){
return 0;
}
int m = intToSort.length/2;
int[] intLeft = new int[m];
stringLeft = new String[m];
int[] intRight = new int[intToSort.length-m];
stringRight = new String[intToSort.length-m];
for (int i=0; i < m; i++){
intLeft[i] = intToSort[i];
stringLeft[i] = stringToSort[i];
}
for (int i = 0;i < intRight.length; i++){
intRight[i] = intToSort[m+i];
stringRight[i] = stringToSort[m+i];
}
inversionsLeft = sortAndCount(intLeft);
inversionsRight = sortAndCount(intRight);
intSorted = new int[intToSort.length];
stringSorted = new String[stringToSort.length];
inversionsMerged = mergeAndCount(intLeft, intRight);
return(inversionsLeft + inversionsRight + inversionsMerged);
}
private static int mergeAndCount(int[] intLeft, int[] intRight){
int count = 0;
int i = 0;
int j = 0;
int k = 0;
while(i < intLeft.length && j < intRight.length){
if(intLeft[i] < intRight[j]){
intSorted[k] = intLeft[i];
stringSorted[k] = stringLeft[i];
i++;
}
else{
intSorted[k] = intRight[j];
stringSorted[k] = stringRight[j];
count += intLeft.length - i + 1;
j++;
}
k++;
}
while (i < intLeft.length)
{
intSorted[k] = intLeft[i];
stringSorted[k] = stringLeft[i];
k++;
i++;
}
while (j < intRight.length)
{
intSorted[k] = intRight[j];
stringSorted[k] = stringRight[j];
j++;
k++;
}
return count;
}
}
int[] intLeft = new int[m];
stringLeft = new String[m];
int[] intRight = new int[intToSort.length-m];
stringRight = new String[intToSort.length-m];
You'll notice here that for the int arrays you are creating new variables, for the string you are replacing the outer. This is making your string arrays smaller with each recursive call whereas your int arrays are passed to each method.
By the time you get to calling mergeAndCount, stringLeft and stringRight are very small whereas the appropriately sized intLeft and intRight are passed as arguments.