Thursday, March 22, 2012

Measuring a string (graphically)

Hi gang,

Is it possible to measure the length (in pixels) of a string ?.

I want to create a function that will determine if a string is longer than Z pixels, if it is, then the function will trim the string's tail and add "..." to it.

Something like:

sVar = "This is a very long string that I want to measure"

sVar = StringTrim(sVar, 125px)

sVar is now: "This is a very long str..."

Any help will be really appreciated.

T.I.A.There's certainly no existing method to do what you ask. While itcould perhaps be done with the System.Drawing classes, it would involve some horribly inefficient code.

As it is, truncating a string in the middle of a word is untidy. Imagine truncating "The CEO is a current member of the Fortune 500 club" at the end of the 15th letter.

You're surely better served by determining a maximum number of characters, and then finding the last whole word within that limit. At that point you add the ellipsis (...).

So, in your example you'd end up with, "This is a very long..."

Much neater.
Hi,

this little code snippet might give you something to start with:


string Truncate(string input, int characterLimit) {
string output = input;

// Check if the string is longer than the allowed amount
// otherwise do nothing
if (output.Length > characterLimit && characterLimit > 0) {

// cut the string down to the maximum number of characters
output = output.Substring(0,characterLimit);

// Check if the character right after the truncate point was a space
// if not, we are in the middle of a word and need to remove the rest of it
if (input.Substring(output.Length,1) != " ") {
int LastSpace = output.LastIndexOf(" ");

// if we found a space then, cut back to that space
if (LastSpace != -1) {
output = output.Substring(0,LastSpace);
}
}
// Finally, add the "..."
output += "...";
}
return output;
}


It was taken from this article:Creating a Custom DataGridColumn Class.

Grz, Kris.

0 comments:

Post a Comment