C# 3.0 C夏普定界符

C# 3.0 C夏普定界符,c#-3.0,C# 3.0,在一个给定的句子中,我想分成10个字符串。字符串中的最后一个单词不应不完整。拆分应基于空格或、或 例如: 这是拉姆。他在mcity工作。 现在10个字符的子串是, 这里是ra。 但产出应该是,, 这是。 最后一个单词不应不完整您可以使用正则表达式检查匹配后的字符是否为单词字符: string input = "this is ram.he"; Match match = Regex.Match(input, @"^.{0,10}(?!\w)"); string result; if (matc

在一个给定的句子中,我想分成10个字符串。字符串中的最后一个单词不应不完整。拆分应基于空格或

例如:
这是拉姆。他在mcity工作。

现在10个字符的子串是,
这里是ra。
但产出应该是,,
这是。

最后一个单词不应不完整

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

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();

不确定这是否是你要找的东西。请注意,这可以做得更干净,但应该让你开始。。。(可能希望使用StringBuilder而不是字符串)

char[]delimiterChars={',',','.','};
string s=“我是拉姆,他在mcity工作。”;
string step1=s.Substring(0,10);//获得前10个字符
string[]step2a=step1.Split(delimiterChars);//获得话语权
string[]step2b=s.Split(分隔符cars);//获得话语权
字符串sFinal=“”;
for(int i=0;i
您如何知道最后一个单词是否不完整?您可以在正则表达式中查找并使用三个分隔符,但不完整性要求需要更多信息。如果第一个单词超过10个字符,该怎么办?您说过字符串拆分应该基于空格*,或者。你没有在空格上分开?为什么你忽略了问号、分号和其他标点符号?如果输入是“12345678…”怎么办?输出是否应为“12345678..”,将省略号部分截断?我真的很想看到更多的例子来说明这应该如何工作,特别是如何处理边缘情况。+1甚至没有考虑使用正则表达式。好多了!
    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 + ".";
    }