Skip to content
Advertisement

Remove a part of string based on its given length with replaceAll in Java

I know that there are different ways to solve this task, but I need a particular way using replaceAll() method. I just stuck with right condition in the expression.

So I have a method like this:

    public static void handleComments(List<Comment> comments, int maxTextLength) {
            comments.replaceAll(comment -> comment.getText().length() > maxTextLength ?  *what should be here?* : comment);
        }

    class Comment {
    private final String text;

    public Comment(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

The case is next: I pass to the method some comments and max length of comment. The method should take list of comments and next, if comment length > maxTextLength, it returns new comment that is a copy of original comment, but shorter (with maxTextLength amount of characters), and if comment length < maxTextLength, it just returns the same comment (or it can be also a copy with the same amount of characters).

Update: Example is below – we have (enter it) limit of 30 characters per string and method cuts all characters in each comment if there are more (>) than 30 characters.

Sample Input:

30

What a nice view! Where is it ?

I do not know, I just found it on the internet!

Perfect!

Sample Output:

What a nice view! Where is it

I do not know, I just found it

Perfect!

Advertisement

Answer

You never showed the comment class. Can we set the text on a comment? Can we create a new one giving the text on the constructor? I am assuming the latter.

Then replace *what should be here?* with

 new Comment(comment.getText().substring(0, maxTextLength-3) + "...")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement