0

这有点令人困惑,但是如果您查看下面的示例,您就会明白!

我有一个特殊的“Console.Write”方法,它接受一个字符串,例如“§cHello %mThere!” 并且在打印到控制台时,此方法会忽略 §c 和 %m(它会更改控制台的颜色)。

现在,我有另一种通过对齐来打印文本的方法,即每隔 n 个字符将字符串分解为字符串数组。这意味着,如果我传递一个 100 个字符和 10 个 LineLength 的字符串,它会将我的字符串分解为一个由 10 个字符串组成的数组,每个字符串有 10 个字符,然后我的 Write 方法将在一个新行中打印每个字符串。

问题是,当我每隔 n 个字符拆分文本时,它会计算 '§' 和 'c' 字符,当我打印它时(打印方法将删除这两个),所以输出会减少两个字符。

所以......我需要一种方法:

  1. 每隔 n 个字符将一个字符串拆分为一个字符串数组。
  2. 但是,它不能将 '§' 和后面的 char 或 '%' 和下一个 char 算作该数学中的字符。
  3. 输出必须在字符串数组中有这些额外的字符。

例子:

string Text = "§cOnce upon a time there was a §R%mnice girl named Cinderella. She was very poor and her father passed way."

int LineLength = 6;

return string[] Output = {
"§conce u" //[o n c e space u], thats 6 chars ignoring the first two.
"pon a "   //[p o n space a space], thats 6 chars.
"time t"   // etc
//etc
}

如果有人帮我写这个,提前谢谢!!!

4

2 回答 2

2

如果我明白你在说什么,这似乎是正确的。

public static string[] ConsoleChunk(string input, int length){
    List<string> Output = new List<string>();
    int k = 0;
    string currentString = "";
    for(int i = 0; i < input.Length; i++){
      if(k == 6){
        Output.Add(currentString);
        currentString = input[i].ToString();
        k = 1;  
      }
      else if(input[i] == '§' || input[i] == '%'){
        currentString += input[i];
        currentString += input[++i];
      }
      else{
        k++;
        currentString += input[i];
      }
      
    }
    Output.Add(currentString);
    return Output.ToArray();
  }

输入

string test = "§cOnce upon a time there was a §R%mnice girl named Cinderella. She was very poor and her father passed way.";

输出

§cOnce u
pon a 
time t
here w
as a §R%mn
ice gi
rl nam
ed Cin
derell
a. She
 was v
ery po
or and
 her f
ather 
passed
 way.
于 2020-08-28T00:43:40.857 回答
0

给定

public static IEnumerable<string> FunkyChunk(string source, int size)
{
   var index = 0;
   while (index < source.Length)
   {
      var sb = new StringBuilder(size*2);
      for (int count = 0; count<size && index < source.Length; index++)
      {
         sb.Append(source[index]);
         if (source[index] != '§' && source[index] != '%')
            count++;
      }

      yield return sb.ToString();
   }
}

注意:这是 O(n) 并且用于StringBuilder更少的分配,即使会有更简洁的解决方案。使用固定缓冲区和另一个索引可能会更好

用法

var input = "012345§678901234567%890123%4567890123456§§789012§345678901234";

foreach (var result in FunkyChunk(input,10))
   Console.WriteLine(result);

输出

012345§6789
01234567%89
0123%456789
0123456§§789
012§3456789
01234

完整的演示在这里

于 2020-08-28T00:28:32.840 回答