2012-10-09 22 views
0

可能重复:
Truncate string on whole words in .Net C#如何显示字符串最多200个字符和剪裁过去的几年charaters直到空白

我必须要显示的消息简要说明让我们说最多200个字符&修剪过去的几个字符,直到空格,我不知道我怎么可以在字符串上这样的行程

Sample te与代码XT

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.

低于输出

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 + "..."; 
    } 

我怎样才能最后几个字符修剪,这样它不会显示字的一部分。我希望你明白我想说的是什么。的的的的的新闻样品新闻样品新闻说明新闻样品新闻说明新闻样品新闻说明新闻样品新闻说明新闻样品新闻描述

所需的输出

样品新闻描述

+4

这个问题已经有了很好的答案。请参阅http://stackoverflow.com/a/1614090/445650 –

+0

@ Kavin,很好完成..谢谢.. – Learning

回答

8

你应该找到200指数之前的空间指数。因此,搜索所有事件,然后挑选一个最接近200的指数,然后使用这个索引做一个子串,你应该是好去

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

int index = myString.LastIndexOf(' '); 

string outputString = myString.Substring(0, index); 
+2

第一行将抛出异常是inputString短于200个字符 – KinSlayerUY

3
if (sDesc.Length > 200) 
{ 
    var str = sDesc.Substring(0, 200); 
    var result = str.Substring(0, str.LastIndexOf(' ')); 
} 
+0

与我发布的代码相同 – middelpat

0

你可以找到200后的空间并采取子,直到第一个空间索引后200

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

string res = sDesc.Substring(0, i); 
1

这将是更快的,因为它在200不先切断,但使用开始和计数的LastIndexOf

参数确实少了一个stringcopy接受的答案
  var lio = inputString.LastIndexOf(' ', 0, 200)); 
      if (lio==-1) lio = 200; 
      var newString = inputString.Remove(lio);