代码之家  ›  专栏  ›  技术社区  ›  SmartestVEGA

基于c中的条件将HTML字符串格式化为红色#

  •  -2
  • SmartestVEGA  · 技术社区  · 6 年前

    我有一个HTML字符串,从SQL数据库中获取值,如下所示

    "100 \n  200 \n 500 \n 1000"
    

    我需要更换 <br> 对于新行,如果值大于或等于500,我还需要将值设置为红色

    我做了如下的替换工作:

      string test = "First line <br/>Second line<br/>First line <br/>Second line";
                  Console.WriteLine(test.Replace("<br/>", "\n" ));
    

    但是我怎么能在这里格式化呢?

    3 回复  |  直到 6 年前
        1
  •  1
  •   Dan Scott    6 年前
    using System.Linq;
    using System.Text;
    
    namespace StringManipulation
    {
        class Program
        {
            static void Main(string[] args)
            {
                string sql = "100 \n  200 \n 500 \n 1000";
                string html = GetHTMLForSQL(sql);
            }
    
            private static string GetHTMLForSQL(string sql)
            {
                int[] values = sql.Split('\n')
                    .Select(s => int.Parse(s.Trim()))
                    .ToArray();
    
                StringBuilder html = new StringBuilder();
                foreach (int val in values)
                {
                    html.Append("<p" + (val >= 500 ? " style='color:red;'" : "") + ">" + val + "</p>");
                }
                return html.ToString();
            }
        }
    }
    

    :)快乐编码

        2
  •  0
  •   Tom Hood    6 年前

    控制台中的格式化可能不是您想象的那样,但如果您想知道如何进行格式化,请执行以下代码:

    using System;
    namespace tests 
    {
        class Program
        {
            static void Main(string[] args)
            {
                int x = 42;
                Console.BackgroundColor = ConsoleColor.Blue;
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("White on blue.");
                Console.WriteLine("Another line.");
                Console.ResetColor();
                Console.WriteLine(x);
            }
        }
    }
    
        3
  •  0
  •   DavidG    6 年前

    你可以用一些林肯来做这个。如果要制作更多的HTML,请始终使用类而不是嵌入格式:

    var input = "100 \n  200 \n 500 \n 1000";
    
    var output = input = string.Join("", input.Split('\n')
        .Select(x => int.Parse(x.Trim()))
        .Select(x => $"<span class=\"{(x >= 500 ? "big-number" : "small-number")}\">{x}</span>"));
    

    其结果是:

    <span class=“small number”>100</span><span class=“small number”>200</span><span class=“big number”>500</span><span class=“big number”>1000</span>

    但是,如果要输出到控制台,可以执行以下操作:

    var output = input.Split('\n')
        .Select(x => int.Parse(x.Trim()));
    
    foreach (var element in output)
    {
        Console.ForegroundColor = element >= 500 
            ? ConsoleColor.Red
            : ConsoleColor.Black;
    
        Console.WriteLine(element);
    }
    

    注意,如果任何值都不能解析为 int ,您应该在生成此生产代码之前修复该问题。