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);
}
}
Related
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));
Hello fellow programmers !
I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array.
For example :-
if the number is 675421.
then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!
Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number to a string.
Then, take each char out of it(in the loop), subtract the ASCII value of 0 from each char to get the digit [ie, ASCII of 0 is 48, 1 is 49, ... ] (see ASCII table)
Do something like this:
String number = "123123";
int[] intArray = new int[number.length()];
for (int i = 0; i < number.length(); i++)
{
intArray[i] = Integer.parseInt(Character.toString(number.charAt(i)));
}
Hope this helps,
Jason.
Below is the recursive solution
public static void main(String[] args) {
int testNum = 675421;
List<Integer> digitList = new ArrayList<Integer>();
collectDigits(testNum, digitList);
Object[] resultArr = digitList.toArray();
int listSize = resultArr.length;
for (int listCount = 0; listCount < listSize; listCount++) {
System.out.println("result["+listCount+"] = "+resultArr[listCount]);
}
}
private static void collectDigits(int num, List<Integer> digits) {
if (num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
One way to do this would be to turn the original integer into a string.
Loop over the string, parsing each character back to an int, and place into the array. Here is an example:
int number = 123456;
String strNumber = number+"";
int[] array = new int[strNumber.length()];
int index = 0;
for(char c : strNumber.toCharArray()){
array[index++] = Integer.parseInt(c+"");
}
System.out.println(Arrays.toString(array));
Math solution, you can split the int number using this:
int[] array = new int[6];
int number = 675421;
array[0] = ((number/100000)%10);
array[1] = ((number/10000)%10);
array[2] = ((number/1000)%10);
array[3] = ((number/100)%10);
array[4] = ((number/10)%10);
array[5] = ((number/1)%10);
If the "number" has a variable length you can automate this, write a coment if you need help
My output should look like:
1 star(*)
3 stars(***)
4 stars(****)
For example i have code:
char array[] = new char[3];
char x = '*';
For (int i= 0; i < array.length; i++)
{
array[i]='*'
x = x+2;
system.out.println(array[i]);
}
No it's not possible in char[] array, you should do it like,
String array[] = new String[3];
String x = "*";
for (int i= 0; i < array.length; i++)
{
array[i] = "";
array[i] = array[i] + x;
system.out.println(array[i]);
x = x + "*";
}
This will print the output as,
*
**
***
Your array is a char array, so each element contains a single char. Therefore your output will be :
*
*
*
To get the output you want, you'll need a String array (or no array at all - you can used a nested loop instead).
In addition, x = x+2; doesn't do what you think it does. It assigns a new character to x. If the initial value of x is '*', it will change it to the char whose numeric value is higher by two compared to the numeric value of '*'.
Just to provide an alternative to the already existing answers, it is also possible to just work with char. The trick then is to use System.out.print() rather than System.out.println(). An example:
int n = 3; //the number of lines you want to print
char x = '*';
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(x);
}
System.out.print("\n");
}
Note: this is just an alternative to the already proposed solutions
For that you need to change array to String type and concat * on it in each level.
Code
String array[] = new String[3];
char x = '*';
array[0]=""+x;
for (int i= 0; i < array.length; i++)
{
System.out.println(array[i]);
if(i!=array.length-1)
array[i+1]='*'+array[i];
}
And you also have so much compilation error in your code like For,Array,system.
Also check DEMO
Considering your out put it can be derived from following
String s="*";
StringBuffer sb =new StringBuffer();
for(int i=1;i<=4;i++)
{
System.out.println(sb.append(s));
}
Output will be
*
**
Tc
How can i get the letter from guess out of alphabet? So if the first guess is AABB i need to get the A and the B out of the String alphabet to make a new random guess without the letters A and B.
randomCode.clear();//Clears the random code ArrayList to put a new one in it
Random r = new Random();
String alphabet = "ABCDEF";
StringBuilder result = new StringBuilder(randomCode.size());
if(turn == 0){
guess = "AABB";
}else{
if(blackPin == 0 && whitePin ==0){
for (int c = 0; c < 4; c++) {
if(alphabet.charAt(c) == guess.charAt(c)){
}
randomCode.add(alphabet.charAt(r.nextInt(alphabet.length())));//generate 4 random letters with the letters ABCDEF and put in arrayList
}
for (Character c : randomCode){//Converts Char[] randomCode to a String
result.append(c);
}
guess = result.toString();//Gives the String guess 4 random letters.
If you have an ArrayList, for example:
ArrayList<Character> alphabet = new ArrayList<>(Arrays.asList('A', 'B', 'C', 'D'));
And a String:
String guess = "AABB";
You can remove from the alphabet each letter which occurs in the guess as shown:
for (int i = 0; i < guess.length(); i++)
alphabet.remove(new Character(guess.charAt(i)));
Now, if print out the alphabet:
for (int i = 0; i < alphabet.size(); i++)
System.out.print(alphabet.get(i));
the output will be: "CD".
You can use this all together:
ArrayList<Character> alphabet = new ArrayList<>(Arrays.asList('A', 'B', 'C', 'D'));
Random random = new Random();
String guess = "";
while (true) {
/* init a guess */
guess = "";
for (int j = 0; j < 4; j++)
guess += alphabet.get(random.nextInt(alphabet.size()));
System.out.println("The guess is: " + guess);
/* remove letters */
for (int j = 0; j < guess.length(); j++)
alphabet.remove(new Character(guess.charAt(j)));
/* the alphabet is empty */
if (alphabet.isEmpty()) {
System.out.println("The alphabet is empty");
break;
}
}
Why loop when you can avoid it:
String abd = "ABCDEF";
String guess = "AABB";
System.out.println(abd.replaceAll(String.join("|", guess.split("")), ""));
This prints:
CDEF
The most efficient way of doing this is to exploit the fact that the ASCII codes of the letters are 26 consecutive integers, and cast from char to int. Codes 65-68 are ABCD.
http://www.ascii-code.com/
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)