truncate string to last full stop (within 160 chars)

S

Stimp

Hi all,

Having a bit of a headache trying to do this.

I want to create a string with a total length of 160 characters.

The first few characters must always be in the string.. say around 45
characters.

After this I want to append another string, description, which can be
any number of characters long.

I want to truncate this string so that when it is appended onto the
other string it doesn't exceed 160 characters BUT I want it truncated
to the nearest '.'.

I've been messing around with substring but not much luck... anyone done
this before?

Cheers,
Peter
 
D

David R. Longnecker

I'm sure someone here can codesmith this a bit better for optimization, but
perhaps this will lead you on the right path.

I left the var names a bit more telling...

string firstString = "Product Name Is Here And is Around 45 Characters
Long.";
int firstStringLength = firstString.Length;

string secondString
= "This is a long description. This long description is really
long. " +
"Boy this is a really long description. Is anyone still reading
this really long description. " +
"Hello out there, are you stil reading? Hello?";

string cutoffString = secondString.Substring(0, 159 - firstStringLength);

int lengthtoLastPeriod = cutoffString.LastIndexOf(".") + 1;

string newString = firstString + " " + cutoffString.Substring(0,
lengthtoLastPeriod);

On the cutoffString, I read your post as if the TOTAL of string1 and string2
could not exceed 160 characters. If that's not the case, remove the "- firstStringLength"
part. :)

Hope this helps!

-dl
 
S

Stimp

Hi all,

Having a bit of a headache trying to do this.

I want to create a string with a total length of 160 characters.

The first few characters must always be in the string.. say around 45
characters.

After this I want to append another string, description, which can be
any number of characters long.

I want to truncate this string so that when it is appended onto the
other string it doesn't exceed 160 characters BUT I want it truncated
to the nearest '.'.

I've been messing around with substring but not much luck... anyone done
this before?

Cheers,
Peter

I got it in the end...

Dim iCharactersAvailable As Integer = 160 - iTotalTextChars

sDescription = sDescription.Substring(0, sDescription.LastIndexOf(".",
iCharactersAvailable, iCharactersAvailable) + 1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top