0

我正在尝试将字符串的一部分转换为不同的对象并将它们加入到列表或数组中,这并不重要。这是一个例子:

示例字符串“这是一个测试字符串。\n \t 这是一个带有制表符的新行”。

我想得到一个输出如下:

new List<OpenXmlElement>(){
                new Text("This is a test string."),
                new Break(),//this is for the \n char
                new TabChar(), //this is for the \t char
                new Text("This is a new line with a tab")
            };

我已经在字典中有一些字符和类类型,我计划使用反射来实例化它们。

public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
    {
              {"\n",   typeof(Break)},
              {"\t",   typeof(TabChar)}
    };

我想我可以使用子字符串或正则表达式,但我希望找到一个更清洁的解决方案。

对不起,如果问题不够清楚。我很乐意回答您的任何问题

这是我的全班

public class FormatConverter:IFormatConverter
{

    public static Dictionary<string, Type> Tags = new Dictionary<string, Type>()
    {
              {"\n",   typeof(Break)},
              {"\t",   typeof(TabChar)}
    };

    public IEnumerable<OpenXmlElement> Convert(string format)
    {
        foreach (KeyValuePair<string,Type> pair in Tags)
        {
            var items = format.Split(
                new []{pair.Key},StringSplitOptions.RemoveEmptyEntries
            );
            foreach (var item in items)
            {
                yield return new Text(item);
                yield return Activator.CreateInstance(pair.Value) as OpenXmlElement;
            }
            format = format.Replace(pair.Key,"");
        }
    }
}

我知道它有什么问题,只是不知道如何解决它。

4

2 回答 2

1

您可以使用 Split() 方法两次。第一次在 "\n" 上拆分时,您可以循环遍历结果,在每个项目之间插入 Break 对象。

然后,您将对 "\t" 的所有子字符串进行拆分,并再次循环在项目之间插入 Tab 对象。

由于您要循环多次,因此不是最有效的,但是递归应该使代码非常简单。

IEnumerable<OpenXmlElement> Convert(string testString) {

    IEnumerable<OpenXmlElement> tabOutput = ConvertString<TabChar>(testString, '\t');

    List<OpenXmlElement> finalOutput = new List<OpenXmlElement>();

    foreach(OpenXmlElement oxe in tabOutput){
        if (oxe is Text)
        {
            IEnumerable<OpenXmlElement> breakOutput = ConvertString<Break>(((Text)oxe).WrappedText, '\n');
            finalOutput.AddRange(breakOutput);
        }
        else
        {
            finalOutput.Add(oxe);
        }
    }
}

IEnumerable<OpenXmlElement> ConvertString<T>(string input, char pattern) 
where T: OpenXmlElement, new() {
    List<OpenXmlElement> output = new List<OpenXmlElement>();

    string[] parts = input.Split( pattern);

    if (parts.Length > 1)
    {
        for (int i = 0; i < parts.Length; i++)
        {
            string part = parts[i];
            if (!string.IsNullOrEmpty(part))
            {
                output.Add(new Text(part));
            }
            if (i < (parts.Length - 1))
            {
                output.Add(new T());
            }
        }
    }
    else
    {
        output.Add(new Text(input));
    }

    return output;
}

您的另一种选择是自己手动遍历字符串并随时构建结果。它可能看起来不是很优雅,但你可以一次性完成。

List<OpenXmlElement> output = new List<OpenXmlElement>();
string testString = "This is a test string.\n \t This is a new line with a tab";

System.Text.StringBuilder currentLine = new System.Text.StringBuilder();
for (int i = 0; i < testString.Length; i++) {
 char curChar = testString[i];

 bool clearCurrLine = true;
 OpenXmlElement objToAdd = null;

 switch (curChar)
 {
    case '\n':
      objToAdd = new Break();
      break;

    case '\t':
      objToAdd = new TabChar();
      break;

    default:
      currentLine.Append(curChar);
      clearCurrLine = false;
      break;
  }

  if (clearCurrLine)
  {
    output.Add(new Text(currentLine.ToString()));
    currentLine.Clear();
    output.Add(objToAdd);
  }
}
if (currentLine.Length > 0)
{
  output.Add(new Text(currentLine.ToString()));
}
于 2013-01-25T00:44:01.633 回答
1

这是一个解析示例文本的解决方案。在实际情况下可能效果不佳:

private readonly static Dictionary<char, Type> Tokens = new Dictionary<char, Type> { 
        { '\n', typeof(Break) },
        { '\t', typeof(TabChar) }
    };

private static IEnumerable<OpenXmlElement> Tokenize(string text)
{
    var start = 0;
    var pos = 0;

    foreach (var c in text)
    {
        Type tokenType;
        if (Tokens.TryGetValue(c, out tokenType))
        {
            if (pos > 0)
            {
                yield return new Text(text.Substring(start, pos));
            }
            yield return (OpenXmlElement)Activator.CreateInstance(tokenType);
            start += pos + 1;
            pos = 0;
        }
        else
        {
            pos++;
        }
    }

    if (pos > 0)
    {
        yield return new Text(text.Substring(start));
    }
}

static void Main(string[] args)
{
    var tokens = Tokenize("This is a test string.\n \t This is a new line with a tab").ToArray();

}
于 2013-01-25T01:55:56.003 回答