算法帮助:按文本框的长度调整文本模糊

时间:2010-07-26 20:40:57

标签: algorithm

我有一个相当不寻常的问题,它伤害了我的大脑。

问题:给定一个已知长度的文本框,以及将进入其中的文本,通过将文本截断为“...”使文本“适合”,使其适合框内。 (上下文:这适用于ASP.NET C#,但我认为该算法与语言无关。)

Example : [_________]
Text :     The big brown dog jumped over the red fence.
Solution :[The bi...]

Example : [_________]
Text :     Ferret
Solution :[Ferret___]

假设:

// Returns the number of px (as an int) that the arg text is in length
public int textLength(String theText, float emSize)

问题:最简单,最快捷的方法是什么?

我害怕通过一次攻击一个角色,添加“......”然后检查长度来做到这一点,因为一些适合的字符串很长。

2 个答案:

答案 0 :(得分:2)

您可以使用正确的长度进行二进制搜索,这意味着您只需要尝试log(n)尺寸。

哦,如果文本是等宽的(每个字符都给出了em的宽度),那么很容易以编程方式解决这个问题:

if str.length * emWidth < textBoxWidth 
   tb.text = str
else
   tb.text = substring(str, 0, round_down(textBoxWidth / emWidth) - 3) + "..."

答案 1 :(得分:1)

为什么从头开始?从头开始并添加字母(和......)直到它不再适合。 :)