【问题标题】:How to access a part of string in c# and put it back?如何在c#中访问字符串的一部分并将其放回去?
【发布时间】:2012-12-17 22:20:33
【问题描述】:

我想从以下字符串中访问字体系列名称,然后在对名称应用过滤器后将其放回原处。这是我的字符串:

font-size:36px;font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;text-align:center;line-height:125%;letter-spacing: 0px;字间距:0px;写作模式:lr-tb;文本锚:中间;填充:#6b055f;填充不透明度:1;笔划:无;字体系列:Abel;-inkscape-字体规范: '亚伯,半粗体'

如何在 c# 中做到这一点?

【问题讨论】:

  • What have you tried?请发布您当前的尝试并说明您遇到的问题。
  • 你知道字符串类是不可变的吗? stackoverflow.com/questions/2365272/why-net-string-is-immutable
  • “放回去”是什么意思?字符串是不可变的,所以做一个子字符串不会改变原来的。没有必要“放回去”。除非您尝试更改它,但如果是这种情况,请更具体。
  • 我认为你们对可变性的了解有点太聪明了。在这种情况下,它是术语,当他们说“替换”时,OP 不会关心实际上创建了一个新字符串,IMO。

标签: c# string


【解决方案1】:

您可以使用String 类,它公开了您需要破解它的所有方法。比如String.IndexOf查找字符或字符串的索引,String.Substring提取,则可以使用String.Replace

这应该足以开始,如果您有与某个问题相关的具体问题,请提出。

【讨论】:

    【解决方案2】:

    你可以使用Regex.Replace:

    string test = "stroke:none;font-family:Abel;-inkscape-font-specification:'Bickham Script Pro Semibold, Semi-Bold'";
    
    // search for the font style
    Regex rex = new Regex(";font-family:.*;");
    
    // replace the font with a new font
    string newString = rex.Replace(test,";font=famliy:Arial;");
    

    【讨论】:

      【解决方案3】:

      我会使用 ASP.NET 的强大功能,而不是自己解析字符串。为什么要重新发明轮子?

      string style = "font-size:36px;font-style:normal;font-variant:normal;font-weight:600;font-stretch:normal;text-align:center;line-height:125%;letter-spacing:0px;word-spacing:0px;writing-mode:lr-tb;text-anchor:middle;fill:#6b055f;fill-opacity:1;stroke:none;font-family:Abel;-inkscape-font-specification:'Abel, Semi-Bold'";
      System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label();
      label.Style.Value = style;
      label.Style["font-family"] = "Verdana";
      style = label.Style.Value;
      label.Dispose();
      

      这也适用于 WinForms,您只需添加对 System.Web 程序集的引用。

      【讨论】:

        【解决方案4】:

        你可以这样做:

        public static class CssStyle
        {
            public static string Update(string style, string key, string value)
            {
                var parts = style.Split(';');
        
                for (int i = 0; i < parts.Length; i++)
                {
                    if (parts[i].StartsWith(key))
                    {
                        parts[i] = key + ":" + value;
                        break;
                    }
                }
        
                return string.Join(";", parts);
            }
        }
        

        这将允许您拥有一个可以更新样式的任何部分的通用函数。如果样式尚不存在,您也可以将其扩展为 添加

        【讨论】:

          猜你喜欢
          • 2011-10-10
          • 2015-04-03
          • 1970-01-01
          • 2015-01-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多