2016-03-31 199 views
1

所以我试图限制一行文本并告诉它何时开始一个新行。 因此,如果输入的文本是大于比12,一个新行将被制作,它会继续。基于字符计数将字符串添加到字符串

到目前为止,我已经有了if语句的开头,然后我迷路了。我查看了从名为inputName的字符串中分支出来的方法,但找不到要搜索的内容。

if (inputName.length() > 12) { 
    inputName. 
} 
+0

所以,你想要将你的字符串分割成长度<= 12的单个字符串,或者你想将新行字符添加到原始字符串中,以便打印字符串将不包含任何长度超过12的行? – Benjamin

+0

第二个选项,其中12个字符后,它开始一个新行,并继续原来的字符串 – FirstOrderKylo

回答

0

你可以这样做。请切断字符串,直到它低于12

while (inputName.length() > 12) { 
    System.out.println(inputName.substring(0,12)); 
    inputName = inputName.substring(12); 
} 
System.out.println(inputName); 
+0

这似乎是折腾错误,说子字符串只接受'substring(int,int)'或'substing(int)' – FirstOrderKylo

+1

再试一次,我修正了它 – wvdz

+0

嗯..这似乎只是由于某些原因删除了前12个字符,(PS:你在while循环中忘了''length'后面的())。 – FirstOrderKylo

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")); 
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 
+0

您的代码会在第一个换行符位于第12个字符后面,但所有后续换行符位于第11个字符后面时生成输出。 –

+0

对不起,我的坏...我已经更新过了。感谢您的检查 – JanLeeYu

0

你要分inputName.length()由12来获得所需的新行数。然后使用for循环和String#substring()添加新行。确保将子字符串偏移1,因为已添加"\n"

例如:

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. 
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个字符添加一行。