【问题标题】:keep linebreaks from multiline textfield in certain sections在某些部分中保留多行文本字段的换行符
【发布时间】:2021-12-23 03:23:47
【问题描述】:

我想提供一种方法来分解多行文本字段的内容并允许为某些部分保留换行符。例如,输入如下所示:

title1: 11.11.2021
title2: documentation
title3: right
Comment: Here 
I still have no 
idea how to keep the 
line breaks

title4: something

我想将整个内容保存在数据结构(键/值)中,并按照最终用户的要求按顺序输出。关键是例如“title1”和值“11.11.2021”。对于评论,该值应该是带有换行符的文本“我仍然在这里......”。不幸的是,我对如何将数据写入多行文本字段没有影响。也可能会添加另一个字段评论。当然我也对其他数据结构开放

如果有任何建议,我将不胜感激。

【问题讨论】:

    标签: c# .net string replace


    【解决方案1】:

    你可以逐行解析,检查是否找到了Key:Value的情况。记住钥匙。如果没有找到 Key:Value 并且您有一个键,则扩展最后一个键值:

    string t = @"title1: 11.11.2021
    title2: documentation
    title3: right
    Comment: Here 
    I still have no 
    idea how to keep the 
    line breaks
    
    title4: something";
    
    var d = new Dictionary<string,string>();
    string key = null;
    
    foreach (var line in t.Replace("\r\n","\n").Split ('\n'))
    {
      var kvp = line.Split (":".ToCharArray (), 2);
    
      if (kvp.Length == 1 && key == null)
        throw new Exception ("First line has no key!");
    
      if (kvp.Length == 1)
      {
        d[key] += $"\r\n{line}";
        continue;
      }
    
      if (kvp.Length == 2)
      {
        key = kvp [0];
        d [key] = kvp [1];          
      }
    }
    
    foreach(var kvp in d)
      Console.WriteLine($"{kvp.Key} = '{kvp.Value}'");
    

    输出:

    title1 = ' 11.11.2021'
    title2 = ' documentation'
    title3 = ' right'
    Comment = ' Here
    I still have no
    idea how to keep the
    line breaks
    '
    title4 = ' something'
    

    【讨论】:

    • 你好帕特里克谢谢你这是一个很好的解决方案。现在我只缺少一个键可以出现两次的问题的解决方案。您可以检查字典中的键包含,但不幸的是,键的值已经在字典中被覆盖。填写字典时我必须重命名密钥,例如评论,评论1,评论2等。你有什么建议给我吗?非常感谢和问候
    • @Tim - 你可以在if (kvp.Length == 2): .. 在插入新的 Key:Value 之前检查 key 是否已经存在。如果是这样,用数字或时间戳或类似的东西修改它。编码愉快。
    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 2021-02-17
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2011-09-26
    • 2013-04-15
    相关资源
    最近更新 更多