2

我正在尝试将一大串文本分成几个较小的文本字符串,并将每个较小的文本字符串的最大长度定义为不同。例如:

"The quick brown fox jumped over the red fence.
       The blue dog dug under the fence."

我希望有可以将其拆分为较小行的代码,并且第一行最多为 5 个字符,第二行最多为 11 个字符,其余的最多为 20 个字符,结果如下:

Line 1: The 
Line 2: quick brown
Line 3: fox jumped over the 
Line 4: red fence.
Line 5:        The blue dog 
Line 6: dug under the fence.

所有这些都在 C# 或 MSSQL 中,有可能吗?

4

2 回答 2

1
public List<String> SplitString(String text, int [] lengths)
{
   List<String> output = new List<String>();

   List<String> words = Split(text);

   int i = 0;
   int lineNum = 0;
   string s = string.empty;
   while(i<words.Length)
   {
       if(s.Length+words[i].Length <lengths[lineNum])
       {
            s+=words[i];
            i++;
            if(lineNum<lengths.Length-1)
                 lineNum++;
       }
       else
       {
          output.Add(s);
          s=String.Empty;
       }

   }

    s.Remove(S.length-1,1);// deletes last extra space.

    return output;
}


   public static List<string> Split(string text)
    {
        List<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();

        foreach (var letter in text)
        {
            if (letter != ' ' && letter != '\t' && letter != '\n')
            {
                sb.Append(letter);
            }
            else
            {
                if (sb.Length > 0)
                {

                    result.Add(sb.ToString());
                }

                result.Add(letter.ToString());
                sb = new StringBuilder();
            }
        }

        return result;
    }

这是未经测试/编译的代码,但您应该明白这一点。

我也认为您应该改用 StringBuilder,但我不记得如何使用它。

于 2010-05-11T23:14:16.503 回答
0
\A(.{0,5}\b)(.{0,11}\b)(.{0,20}\b)+\Z

将在第 1 组中捕获最多 5 个字符,在第 2 组中最多捕获 11 个字符,在第 3 组中最多捕获 20 个块。匹配项将沿单词分隔符拆分,以避免在单词中间拆分。空格、换行符等算作字符并将被保留。

诀窍是获取重复组中的单个匹配项,这只能在 .NET 和 Perl 6 中完成:

Match matchResults = null;
Regex paragraphs = new Regex(@"\A(.{0,5}\b)(.{0,11}\b)(.{0,20}\b)+\Z", RegexOptions.Singleline);
matchResults = paragraphs.Match(subjectString);
if (matchResults.Success) {
    String line1 = matchResults.Groups[1].Value;
    String line2 = matchResults.Groups[2].Value;
    Capture line3andup = matchResults.Groups[3].Captures;
    // you now need to iterate over line3andup, extracting the lines.
} else {
    // Match attempt failed
} 

我根本不懂 C#,并试图从 RegexBuddy 的模板和此处的 VB 代码构建它,所以请随时指出我的编码错误。

请注意,第二行开头的空格是在上一场比赛结束时捕获的。

于 2010-05-12T14:35:46.400 回答