0

So I am running a string append statement inside a for loop

String apComment;
apComment = ''; 
for(Processinstancehistory p:lispros)
{
    apComment +=p.Comments;
}

So after this, I get the comments in below way

Comment1nullComment2Comment3

I get a null in between. Can someone please help how to remove this null

0

+Dan's response..

You can use null check before appending it to your string..

String apComment = ''; 
for(Processinstancehistory p:lispros)
{
    if (string.isNotBlank(p.Comments)) {
        apComment +=p.Comments;
    }
}

or you can create a list of comments and use string.join as suggested..

String apComment = '';
List<String> comments = new List<String>();
for(Processinstancehistory p:lispros)
{
    if (string.isNotBlank(p.Comments)) {
        comments.add(p.Comments);
    }
}

if (!comments.isEmpty()) {
    apComment = string.join(comments, ',');
}
1
  • it worked ,thank you . Also I am getting all the commments in 1 line . Do you know how can I apply line breaks here . '/n' is not working as I am displaying the comments in email template – user75937 Dec 4 '19 at 8:57
0

I'd recommend using String.join() instead of trying to handle the concatenation yourself. This really goes for anything where Salesforce provides us with standard logic they've built themselves. It saves us time, is probably better-written, and is almost certainly better-optimized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.