首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何生成多行注释

如何生成多行注释
EN

Stack Overflow用户
提问于 2014-09-12 21:53:02
回答 1查看 909关注 0票数 1

在stringtemplate-4中,如何生成多行注释?例如,模板如下所示(注释的开始和结束位于其他模板中):

代码语言:javascript
复制
test(DESCRIPTION) ::= <<
*
* <DESCRIPTION>
*
>>

而DESCRIPTION是一个很长的字符串,也可以包含换行符,例如:

代码语言:javascript
复制
"This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line."

因此,我们希望输出字符串如下:

代码语言:javascript
复制
*
* This is a small description of the program,
* with a line-width of 50 chars max, so the
* line is split.
* Final line.
*
EN

回答 1

Stack Overflow用户

发布于 2014-11-08 05:27:02

看起来你想在这里做几件事--把描述放在以星号开头的一行上,但是如果有换行符或者长度大于50,就把它放在单独的一行上。

首先,在将描述传递给模板之前,我会根据换行符和长度在视图模型中拆分描述。

然后,我对模板做了一个小改动,用换行符和星号分隔数组中的每一项。

以下是组文件test.stg:

代码语言:javascript
复制
group test;

description(lines) ::= <<
*
* <lines; separator="\n* ">
* 
>>

我不确定您在视图模型中使用的是哪种语言,但这里有一些Java:

代码语言:javascript
复制
public static void main(String[] args) {
    STGroup templates = new STGroupFile("test.stg");
    String description = "This is a small description of the program, with a line-width of 50 chars max, so the line is split.\nFinal line.";
    // we add two characters at the start of each line "* " so lines can now
    // be only 48 chars in length
    description = addLinebreaks(description, 48);
    String lines[] = description.split("\\r?\\n");
    ST descTemplate = templates.getInstanceOf("description");
    for (String line : lines)
    { 
        descTemplate.add("lines", line);
    }
    System.out.println(descTemplate.render());
}


// used to add line breaks if the length is greater than 50
// From this SO question: http://stackoverflow.com/questions/7528045/large-string-split-into-lines-with-maximum-length-in-java
public static String addLinebreaks(String input, int maxLineLength) {
    StringTokenizer tok = new StringTokenizer(input, " ");
    StringBuilder output = new StringBuilder(input.length());
    int lineLen = 0;
    while (tok.hasMoreTokens()) {
        String word = tok.nextToken()+" ";

        if (lineLen + word.length() > maxLineLength) {
            output.append("\n");
            lineLen = 0;
        }

        output.append(word);
        lineLen += word.length();
    }
    return output.toString();
}

我得到的输出是:

代码语言:javascript
复制
*
* This is a small description of the program, 
* with a line-width of 50 chars max, so the line 
* is split.
* Final line. 
*

它看起来与您的示例略有不同,但确实达到了50个字符的限制。我想您可以尝试它,直到它符合您的需求。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25809946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档