简体   繁体   English

如何向 stringbuilder 添加另一个字符串?

[英]How can I add another string to stringbuilder?

I have this part of code which I don't understand correctly.我有这部分代码我不能正确理解。 I know that it builds a string out of values from the database.我知道它会根据数据库中的值构建一个字符串。 I think it's only the title :我认为这只是title

private String createSearchFieldContent(Report report) {
  return createSearchFieldContent(report.getTitle(), report.getDescription());
}

private String createSearchFieldContent(OverrideableStringValue title,
                                        OverrideableStringValue description) {

  StringBuilder builder = new StringBuilder(getValue(title));
  if (StringUtils.isNotBlank(getValue(description))) {
    builder.append(" ").append(getValue(description));
  }
  String searchTerm = StringUtils.replaceAll(builder.toString(), "\n", " ");
  return unaccent(searchTerm);
}

I have another value which I'd like to add to the searchTerm .我有另一个值要添加到searchTerm It's stored in report.getOwner() .它存储在report.getOwner()中。 How is it possible that I can build a new searchTerm which includes the title , description and owner ?我怎么可能构建一个包含titledescriptionsearchTerm的新搜索owner

Thanks!谢谢!

Try below code:试试下面的代码:

private String createSearchFieldContent(Report report) {
  return createSearchFieldContent(report.getTitle(), report.getDescription(), report.getOwner());
}

private String createSearchFieldContent(OverrideableStringValue title,
                                        OverrideableStringValue description, OverrideableStringValue owner) {

  StringBuilder builder = new StringBuilder(getValue(title));
  if (StringUtils.isNotBlank(getValue(description))) {
    builder.append(" ").append(getValue(description));
  }
  if (StringUtils.isNotBlank(getValue(owner))) {
    builder.append(" ").append(getValue(owner));
  }
  String searchTerm = StringUtils.replaceAll(builder.toString(), "\n", " ");
  return unaccent(searchTerm);
}

In the above code, we are passing the owner attribute to the createSearchFieldContent method like the other two, then the owner attribute is appended to string builder object just like description.在上面的代码中,我们像其他两个一样将所有者属性传递给createSearchFieldContent方法,然后将所有者属性附加到字符串生成器 object 就像描述一样。

You can assign new data to searchTerm:您可以将新数据分配给 searchTerm:

searchTerm = StringUtils.replaceAll(builder.toString(), "\n", " ")

becomes变成

String part2 = "something you want to add"; 
searchTerm = searchTerm + part2;

Or you could use the StringBuilder to append new data to或者您可以使用 StringBuilder 到 append 新数据

builder.append("new data")
builder.append("newer data")

This gets added to the StringBuilder which is incorporated in the string value of searchTerm.这被添加到 StringBuilder 中,该 StringBuilder 包含在 searchTerm 的字符串值中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM