字符串处理:
在类MyWindow类中设计一个方法showMyAscWindow(String toShowString),满足要求:在指定一个矩形框中放入指定的文本串。
形如:(注意使用等宽字体来查看效果! 如Courier New字体)
----------------------------------
| This is a test program of long |
| text enclosed in a given ASCII |
| Window. It's important in old |
| days to process codes. |
---------------------------------- ----------------------------------
| This is a test of short string |
---------------------------------- ----------------------
| This is a test of |
| short string |
---------------------- ----------
| This |
| is |
| a |
| test |
| of |
| short |
| string |
----------
要求外部的框有弹性,即适应里面包容的字符串,同时要求对其中的字符串进行断字,以防止将单词分割到两行中去。要求在窗体左右两边留有一个字符的空白。
外部窗体(字符框)可以指定宽度和高度,当内部字符太多,自己设计策略调整,是优先满足宽度还是优先满足高度,或者使窗体总是保持长宽的比例。**************************************************************
刚接触java 遇上这种题型 以前没有遇见过 请高手指点一下 请说明思想和代码 谢谢
在类MyWindow类中设计一个方法showMyAscWindow(String toShowString),满足要求:在指定一个矩形框中放入指定的文本串。
形如:(注意使用等宽字体来查看效果! 如Courier New字体)
----------------------------------
| This is a test program of long |
| text enclosed in a given ASCII |
| Window. It's important in old |
| days to process codes. |
---------------------------------- ----------------------------------
| This is a test of short string |
---------------------------------- ----------------------
| This is a test of |
| short string |
---------------------- ----------
| This |
| is |
| a |
| test |
| of |
| short |
| string |
----------
要求外部的框有弹性,即适应里面包容的字符串,同时要求对其中的字符串进行断字,以防止将单词分割到两行中去。要求在窗体左右两边留有一个字符的空白。
外部窗体(字符框)可以指定宽度和高度,当内部字符太多,自己设计策略调整,是优先满足宽度还是优先满足高度,或者使窗体总是保持长宽的比例。**************************************************************
刚接触java 遇上这种题型 以前没有遇见过 请高手指点一下 请说明思想和代码 谢谢
----------------------------------
| This is a test program of long |
| text enclosed in a given ASCII |
| Window. It's important in old |
| days to process codes. |
---------------------------------- ----------------------------------
| This is a test of short string |
---------------------------------- ----------------------
| This is a test of |
| short string |
---------------------- ----------
| This |
| is |
| a |
| test |
| of |
| short |
| string |
----------
如果优先保证高度,那就要先计算宽度。指定宽度的断字算法如下:
首先将字符串用空格分解到 String[]
然后从0开始,依次累加String[i].length(), 没超过宽度就+1(字与字之间要一个空格),然后重复;
当累积长度大于宽度后,将刚刚的字合并到一个字符串里,把后面差的空格补齐,把你的矩形的框框的"|"字符加上,再加上回车
这样重复,直到处理完成。指定高度,计算宽度的方法如下:
首先计算所有字符串的长度,除以高度,就是最小宽度。
从最小宽度开始,遍历整个字符串,碰到某个位置不是空格,就断在这个字前面。 最后如果高度满足要求,就是这个宽度了;
如果不能满足要求(一般第一个最小宽度肯定是不满足的),那么最小宽度增加。 然后再试。
每次最小宽度增加多少呢? newMinWidth = string.indexof(" ", minWidth+1). 就是增加下一个字的字长而已。
这句话说的含糊,意思是这样:
从最小宽度开始,以这个宽度去切这个字符串,碰到某个位置不是空格,就断在这个字前面。 一直重复,知道整个字符串处理完。最后如果高度满足要求,就是这个宽度了;
例如:
minWidth=12;
String string = "this is a test string for broken word";
那么处理过程就类似这样
int pos=0; int lines = 0;
while(pos < string.length){
lines ++;
if (string.charAt(pos+minWidth) == ' '){
pos += minWidth;
}else{
pos = string.lastIndexof(" ", pos+minWidth);
}
}
如果lines不超过指定的高度,就OK。 否则,minWidth要增加