0

Possible Duplicate:
Truncate string on whole words in .Net C#

I have to display brief description of the news let us say maximum of 200 characters & trim the last few characters till white-space, I am not sure how i can trip this kind on string

Sample text

sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news.

OUTPUT with code below

sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample n

    if (sDesc.Length > 200)
    {
        sDesc = sDesc.Substring(0, 200);
       // sDesc = sDesc + "...";
    }

how can i trim last few characters so that it doesn't show part of word. I hope you have understood what i am trying to say.

Desired OUTPUT

sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample news description of news sample

Community
  • 1
  • 1
Learning
  • 19,469
  • 39
  • 180
  • 373

4 Answers4

9

You should find the index of the space right before the 200 index. So search for all occurrences and then pick the index of the one the closest to 200. Then use this index to do a Substring and you should be good to go

string myString = inputString.Substring(0, 200);

int index = myString.LastIndexOf(' ');

string outputString = myString.Substring(0, index);
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
middelpat
  • 2,555
  • 1
  • 20
  • 29
3
if (sDesc.Length > 200)
{
    var str = sDesc.Substring(0, 200);
    var result = str.Substring(0, str.LastIndexOf(' '));
}
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
1

This will be quicker as the accepted answer as it does one less stringcopy by not first cutting off at 200, but using the start and count parameters of LastIndexOf

            var lio = inputString.LastIndexOf(' ', 0, 200));
            if (lio==-1) lio = 200;
            var newString = inputString.Remove(lio);
IvoTops
  • 3,463
  • 17
  • 18
0

You can find the space after 200 and take substring till first space after index 200.

int i = 200;
for(i=200; i < sDesc.Length; i++)
{
      if(input[i] == ' ')
         break;
}

string res = sDesc.Substring(0, i);
Adil
  • 146,340
  • 25
  • 209
  • 204