Skip to content

How to make equal two char arrays by adding ‘0’? Java

I got some problem. I have two char arrays (for ex. char[] number1 = {‘1′,’1′,’1′,’1’}, and char[] number2 {‘2′,’2’}). And now I want to return array with same length what number1 is, but in indexes on the left where add ‘0’ (for ex. in this case => {‘0′,’0′,’2′,’2’}

I try something like this:

public static char[] whichShorter(char[] first,char[] secend){

    if(first.length >= secend.length) return secend;
        else return first;

}

public static char[] whichLonger(char[] first,char[] secend){

    if(first.length >= secend.length) return first;
    else return secend;

}

public static char[] makeEqual(char[] first, char[] secend){
  char[] longer = whichLonger(first,secend);
  char[] shorter =  whichShorter(first, secend);
  char[] addZero = new char[longer.length];
  

    for (int i = shorter.length; i >0 ; i--) {

        addZero[i]=shorter[i-1];

    }

    for (int i = 0; i < addZero.length ; i++) {

        if(addZero[i]==(char) 0) addZero[i]='0';

    }
    
    return addZero;

}

I guess its not hard at all, but im trying hard and there no effect (I try to draw on paper first, everything).

Answer

You can do:

Stream<Character> leadingZeros = IntStream.range(0, number1.length - number2.length)
        .mapToObj(i -> '0');
Stream<Character> originalChars = IntStream.range(0, number2.length)
        .mapToObj(i-> number2[i]);

Character[] newNumber2 = Stream.concat(leadingZeros, originalChars).toArray(Character[]::new);

System.out.println(Arrays.toString(newNumber2));

Input 1:

char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2'};

Output 1:

[0, 0, 2, 2]

Input 2:

char[] number1 = {'1','1','1','1'};
char[] number2 = {'2','2', '2', '2', '2'};

Output 2:

[2, 2, 2, 2, 2]