Link to home
Start Free TrialLog in
Avatar of Paul Kahl
Paul KahlFlag for United States of America

asked on

Trimming a string to shorten at an unspecified position.

Given:
  1. variable length string, output from database
  2. Need to display no MORE than 80 characters
  3. Cannot end string on broken word (for instance, cutting at exactly 80 characters would be bad if it cuts a word in half)

The idea here is that I have a string from a field in a database. I want to trim it to 80 characters or as close to 80 without going over as I can get, without cutting any words in half.

To help, in ASP classic (which I'm converting from, to C#), I did it like this:

shortBody = Left(objRS(8), InStrRev(Left(objRS(8), 80), " "))


C# Only please.
Avatar of bastibartel
bastibartel

int pos=1000;

CString String( "...long text ...");

int pos = String.ReverseFind(' ');
while(pos>80)
{
   pos = String.ReverseFind(' ');
   if (pos>=0)
        String = String.Left(pos);
}
Sry, I clicked too soon,

CString String( "...long text ...");

int pos = String.ReverseFind(' ');
while(pos>80)
{
   String = String.Left(pos);
   pos    = String.ReverseFind(' ');
}
if (pos >0)
    return String.Left(pos);
else
   return "";

Oh, and I don't know, is CString C# ?
Avatar of Paul Kahl

ASKER

cStr is VB, but I get the gist... refactoring and testing now...
ASKER CERTIFIED SOLUTION
Avatar of devsolns
devsolns

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Tested both of your answers, and discovered too many errors in Basti's to be able to easily refactor. Devsolns' answer was dead on, no need to refactor.

Thanks muchly for the help!
Modified to take input of desired length:

public string RenderBodyTextShort(string inputString, int intDesiredStringLength)
    {
        if (inputString.Length <= intDesiredStringLength)
        {
            return inputString;
        }
        else
        {
            inputString = inputString.Substring(0, intDesiredStringLength);
            if (inputString.Substring(49, 1) != " ")
            {
                int lastSpaceIndex = inputString.LastIndexOf(" ");
                if (lastSpaceIndex == -1)
                    return inputString;
                return inputString.Substring(0, lastSpaceIndex);
            }
            else
            {
                return inputString;
            }
        }
    }
Yeah sry, was missing a compiler. Take care,
Sebastian