2016-03-31 195 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個字符添加一行。