基于字符计数向字符串添加新行

时间:2016-03-31 00:01:39

标签: java string

所以我试图限制一行文字并告诉它何时开始一个新行。 因此,如果输入的文本大于大于12,则会生成一个新行并继续。

到目前为止,我已经得到了if语句的开头,然后我就输了。我已经查看了名为inputName的字符串中的分支方法,但无法找到我正在搜索的内容。

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ]
}

5 个答案:

答案 0 :(得分:0)

你可以这样做。继续切断弦,直到它低于12。

{{1}}

答案 1 :(得分:0)

 String inputName="1234567890121234567890121234567890121234567890121234567890";
 while (inputName.length() > 12) {
        System.out.print(inputName.substring(0,12)+System.getProperty("line.separator"));
        inputName = inputName.substring(12);
 }
 System.out.print(inputName+System.getProperty("line.separator"));

答案 2 :(得分:0)

以下是您可以采取的措施:

    String inputname = "This is just a sample string to be used for testing";

    for (int i = 12; i < inputname.length(); i+= 13) {
        inputname = inputname.substring(0, i) + "\n" + inputname.substring(i, inputname.length());
    }
    System.out.println(inputname);

OUPUT:

This is just
 a sample st
ring to be u
sed for test
ing

答案 3 :(得分:0)

您应该将inputName.length()除以12,以获得所需的新行数。然后使用for循环和String#substring()添加新行。由于添加了"\n",因此确保将子字符串偏移1。

例如:

public static void main(String[] args) {
    final int MAX_LENGTH = 12;
    String foo = "foo foo foo-foo foo foo-foo foo foo-foo.";

    // only care about whole numbers
    int newLineCount = foo.length() / MAX_LENGTH;

    for (int i = 1; i <= newLineCount; i++) {
        // insert newline (\n) after 12th index
        foo = foo.substring(0, (i * MAX_LENGTH + (i - 1))) + "\n"
                + foo.substring(i * MAX_LENGTH + (i - 1));
    }

    System.out.println(foo);
}

输出:

foo foo foo-
foo foo foo-
foo foo foo-
foo.

答案 4 :(得分:0)

如果要将字符串存储在内存中,则可以执行

StringBuilder sb = new StringBuilder();
for (int begin = 0, end = begin + 12; begin < src.length()
        && end < src.length(); begin += 12, end = begin + 12) {
    sb.append(src.substring(begin, end));
    sb.append('\n');
}
System.out.println(sb);

它遍历字符串并为每12个字符附加一个新行。

相关问题