JetBrains Academy: StringBuilder - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: StringBuilder

Concat all strings without digits:

Implement a method to concatenate all strings from the given array to a single long string. You must skip all digits inside the input strings.

Use StringBuilder to solve the problem, because the input array can contain a huge number of strings.

import java.util.Scanner;
import java.util.stream.Stream;

class ConcatenateStringsProblem {

    public static String concatenateStringsWithoutDigits(String[] strings) {
        // write your code with StringBuilder here
        StringBuilder concatenated = new StringBuilder();
        
        for (String elem : strings) {
            concatenated.append(elem);
        }
        
        for (int i = 0; i < concatenated.length(); i++) {
            char currentCharacter = concatenated.charAt(i);
            if (Character.isDigit(currentCharacter)) {
                concatenated.deleteCharAt(i);
                i--;
            }
        }
        
        return concatenated.toString();
        
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] strings = Stream
                .of(scanner.nextLine().split("\\s+"))
                .toArray(String[]::new);

        String result = concatenateStringsWithoutDigits(strings);

        System.out.println(result);
    }
}

or

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Stream;

class ConcatenateStringsProblem {

    public static String concatenateStringsWithoutDigits(String[] strings) {
        // write your code with StringBuilder here
        StringBuilder concatenated = new StringBuilder();

        Arrays.stream(strings).forEach(concatenated::append);

        String[] characters = concatenated.toString().split("");

        return Arrays.stream(characters)
                     .filter(elem -> Character.isLetter(elem.charAt(0)))
                     .reduce("", (partialString, element) -> partialString + element);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] strings = Stream
                .of(scanner.nextLine().split("\\s+"))
                .toArray(String[]::new);

        String result = concatenateStringsWithoutDigits(strings);

        System.out.println(result);
    }
}