Java StringBuilder:x Chars后的换行符,不分割单词

时间:2015-12-16 00:02:52

标签: java string newline stringbuilder

public class Ex7
    {
        //constructor
        public static String s = "1234567890123456789 In the output words on a line are separated by precisely one space verb+' '+,\nlines are separated by\n\nprecisely one newline (so no trailing spaces) and";
        public static int width = 20;

        public static void format(){
            StringBuilder sb = new StringBuilder();
            for(int start = 0; start < s.length(); start += width){
                int cursor = start + width - 1;
                boolean w = true;
                while(w){
                    if(cursor-1 < s.length()){
                        if((s.charAt(cursor) == ' ') || (s.charAt(cursor)== '\t')){
                            if(start + width -1 < s.length()){
                                sb.append(s.substring(start, cursor));
                                sb.append("\n");
                                w = false;
                            }
                            else{
                                sb.append("\n");
                                sb.append(s.substring(start));
                                w = false;
                            }      
                        }
                        else{
                            cursor--;
                        }
                    }
                    else{
                       sb.append("\n");
                       sb.append(s.substring(start));
                       w = false; 
                    }
                }
            }
            System.out.println(sb);
            }
    }

嘿伙计们,

我的目标是,格式化给定的String,以便在每20个字符之后有一个换行符(在本例中)。单词可能不会分开(如果第20个字符是单词的一部分,则必须在该单词之前插入换行符。)

我的输出与此示例 - 字符串:

1234567890123456789
In the output words
on a line are
ted by precisely
 space verb+'
nes are separated


precisely one
ine (so no trailing

spaces) and

锻炼所需的输出:

01234567890123456789
In the output words
on a line are
separated by
precisely one space
\verb+' '+, lines
are separated by
precisely one
newline (so no
trailing spaces)
and

我们可能不会使用Scanner类或第三方库。 有什么建议吗?

此致 FLiiX

1 个答案:

答案 0 :(得分:0)

for(int i=0; i<s.length(); )
{
   if(!(s.substring(i+21).equals(" ")))
   {
      int j = i+21;
      do
      {
         j--;
      }while(!(s.substring(j).equals(" ")));
      System.out.print(s.substring(i, j) + "\n");
      i += i - j;
   }else{
      System.out.print(s.substring(i, i+20) + "\n");
      i += 20;
   }
}

我还没有对此进行测试,但我相信它可以达到您的目的。