Truncate String

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

How can I truncate a string so it does not get more than 120
characters?
I would need the last word to not be broken. For example:

For example, for this phrase:
"...and I sent a post to charp forum"

This would be ok:
"...and I sent a post to charp"

This wouldn't be ok:
"...and I sent a post to charp for"

Thanks,
Miguel
 
shapper said:
How can I truncate a string so it does not get more than 120
characters?
I would need the last word to not be broken. For example:

For example, for this phrase:
"...and I sent a post to charp forum"

This would be ok:
"...and I sent a post to charp"

This wouldn't be ok:
"...and I sent a post to charp for"

Something like:

if(s.Length > 120)
{
int ix = 120;
while(ix > 0 && s[ix] != ' ') ix--;
s = s.Substring(0, ix);
}

Arne
 
(...)
How can I truncate a string so it does not get more than 120
characters?
I would need the last word to not be broken. For example:
(...)

Try this:

private string TruncateToWord(string str, int length)
{
string result = str.Substring(0, length);
if (str.Length <= length || length == 0 || str[length - 1].Equals(' '))
return result;
int i = length;
while (i>0 && !result[i-1].Equals(' ')) i--;
return result.Substring(0, i);
}

Dawid Rutyna
 
Back
Top