In the text, words of a given length are replaced by a specified substring of arbitrary length

Viewed 33

I need to replace all words given length by random substring of arbitraty lenght.For example, the length given word is 3, thus i need to replace "the" to "a"

String str = "Java is the best language in the world!";
String randomWord = "a"; 
//Manipulations
System.out.println(str);
// Outputs: Java is a best language in a world!
2 Answers

An algorithm like this should work:

String str = "Java is the best language in the world!";
String randomWord = "a";
int givenLength = 3;

// Split the string into an array containing each word:
String arr[] = str.split(" ");

// Loop through and find & replace all words of the given length
for (int i=0; i<arr.length; i++){
    if (arr[i].length() == givenLength) {
        arr[i] = randomWord;
    }
}

// Rejoin words into a new string
String output = String.join(" ",arr);
    public static void main(String[] args) {
        String str = "Java is the best language in the world!";
        int wordLength = 3;
        String replaceWord = "a";
        Function<String, String> replaceFunction = element -> {
            if (element.toCharArray().length == wordLength) {
                return replaceWord;
            } else {
                return element;
            }
        };
        String result = Arrays.stream(str.split(" "))
                .toList()
                .stream()
                .map(replaceFunction)
                .collect(Collectors.joining(" "));
        
        System.out.println(result);
    }
Related