tags:

views:

41

answers:

2

I have a rather unusual problem, and it is hurting my brain.

Problem: Given a textbox of known length, and the text that will go inside it, make the text "fit" by truncating it with room for "..." to fit inside the box. (Context : This is for ASP.NET C#, but I think the algorithm is language agnostic.)

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

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

Given:

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

Question: What is the simplest and fastest way to do this?

I am afraid to do it by hacking off one character at a time, adding "..." and then checking the length because some of the strings to fit are veeeeery long.

+1  A: 

Why start from end? Start from the beginning and add letters (and ...) until it no longer fits. :)

Mchl
+1. If the performance of this is non-negligable, then it's probably a GUI WTF in itself since you have an extremely long text box. May not apply for text areas though.
Mark Peters
Just as a point of comparison, if you have a 50 char text box my way is faster up to about 1 quadrillion characters. But the code is more complex.
Mark Peters
Because some textboxes can fit strings up to perhaps 200ish characters.
rlb.usa
From the other end of the spectrum, the strings to fit can possibly be as large as 900 characters (that's a lot of pixels in length!)
rlb.usa
@Mark Peters A context sidenote, this is for getting the string to fit visibly in the textbox - so it can be printed as a pre-filled out PDF form. : ) Even though this is not what I was looking for, I like it because it is so simple.
rlb.usa
+2  A: 

You could do a binary search on the correct length instead, which means you only have to try log(n) sizes.

Oh, also if the text is monospaced (every character is given the width of an em) then it's pretty easy to figure this out programatically:

if str.length * emWidth < textBoxWidth 
   tb.text = str
else
   tb.text = substring(str, 0, round_down(textBoxWidth / emWidth) - 3) + "..."
Mark Peters
I guess checking the ratio of textbox and string lengths first could be used to find starting point
Mchl
Thank you for including the name of the algorithm 'binary search'. Couldn't remember what this was called.
rlb.usa