2010-07-30 42 views
2

在给定的句子中,我想分成10个字符串。字符串中的最后一个单词不应该不完整。分割应根据空间或,.C清晰分隔符

例如进行: this is ram.he works at mcity.

现在的10个字符的字符串是, this is ra. 但输出应该是, this is. 最后一个字不应该是不完整

+0

你怎么知道最后一个词是不完整的?您可以查找三个分隔符的正则表达式,然后使用它,但不完整性需求需要更多信息。 – 2010-07-30 11:50:41

+0

如果第一个单词超过10个字符会发生什么? – 2010-07-30 11:51:11

+0

你说的字符串分割应该基于SPACE *或。你没有在空间上分裂? – Nix 2010-07-30 12:24:07

回答

2

您可以使用正则表达式来检查匹配后的字符不是单词字符:

string input = "this is ram.he"; 

Match match = Regex.Match(input, @"^.{0,10}(?!\w)"); 
string result; 
if (match.Success) 
{ 
    result = match.Value; 
} 
else 
{ 
    result = string.Empty; 
} 

结果:

this is 

的另一种方法是建立串起来的记号标记,直到将另一个令牌会超出字符限制:

StringBuilder sb = new StringBuilder(); 
foreach (Match match in Regex.Matches(input, @"\w+|\W+")) 
{ 
    if (sb.Length + match.Value.Length > 10) { break; } 
    sb.Append(match.Value); 
} 
string result = sb.ToString(); 
+0

+1甚至没有考虑使用正则表达式。好多了! – 2010-07-30 12:39:33

0

如果不知道是你正在寻找的东西。请注意,这可以做得更干净,但应该让你开始......(可能要使用StringBuilder而不是String)。

char[] delimiterChars = { ',', '.',' ' }; 
    string s = "this is ram.he works at mcity."; 

    string step1 = s.Substring(0, 10); // Get first 10 chars 

    string[] step2a = step1.Split(delimiterChars); // Get words 
    string[] step2b = s.Split(delimiterChars);  // Get words 

    string sFinal = ""; 

    for (int i = 0; i < step2a.Count()-1; i++)  // copy count-1 words 
    { 
     if (i == 0) 
     { 
      sFinal = step2a[i]; 
     } 
     else 
     { 
      sFinal = sFinal + " " + step2a[i]; 
     } 
    } 

    // Check if last word is a complete word. 

    if (step2a[step2a.Count() - 1] == step2b[step2a.Count() - 1]) 
    { 
     sFinal = sFinal + " " + step2b[step2a.Count() - 1] + "."; 
    } 
    else 
    { 
     sFinal = sFinal + "."; 
    }