Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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) + "...")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading