Home > database >  In the text, words of a given length should be replaced with the assigned string(some random words).
In the text, words of a given length should be replaced with the assigned string(some random words).

Time:10-27

It is forbidden to use regular expression processing tools: java.util.regex package classes (Pattern, Matcher, etc.), as well as methods of the String class (matches, replace, replaceFirst, replaceAll, split). use StringBuilder or StringBuffer. Help do the task.

public static void main(String[] args) {
        String[] arr = new String[4];
        arr[0] = "I";
        arr[1] = "love";
        arr[2] = "orange";
        arr[3] = "juice.";
        System.out.println(arr[0] " "  arr[1] " "   arr[2] " "  arr[3]); // I love orange juice
        String randomWord = "crazy impressed of ";
        int givenLength = 4;
        for (int i=0; i<arr.length; i  ){
            if (arr[i].length() == givenLength) {
                arr[i] = randomWord;
            }
        }
        String output = String.join(" ",arr);
        System.out.println(output); // I crazy impressed of orange juice
        }

I must use StringBuilder and StringBuffer in my code, but i don`t know how to do this. Help me pls. You can use classes

CodePudding user response:

Probably you need something like:

public static void main(String[] args) {
    String input = "all words like willbereplaced with length like word replacedwillbe";
    int givenLength = 14;
    StringBuilder builder = new StringBuilder();
    int currentWordLength = 0;
    for(char let: input.toCharArray()) {
        if(' ' == let){
            if(currentWordLength == givenLength) {
                builder.replace(builder.length() - givenLength, builder.length(), getRandom());
            }
            currentWordLength = 0;
        } else {
            currentWordLength  ;
        }
        builder.append(let);
    }
    if(currentWordLength == givenLength) {
        builder.replace(builder.length() - givenLength, builder.length(), getRandom());
    }

    System.out.println(input);
    System.out.println(builder.toString());
}

static String getRandom() {
    return Math.random() < 0.5 ? "random1" : "random2";
}
  • Related