【问题标题】:Printing c# reserved keywords in colors以颜色打印 c# 保留关键字
【发布时间】:2012-03-09 17:11:00
【问题描述】:

好的,在我的记事本之类的程序中,我想像代码一样打印文本,所以我希望保留字以蓝色打印,文本在页边距内有什么想法吗? 这是我目前所拥有的。

    int charPag = 0;
        int linPag = 0;
        Font rodFont = new Font("Courier New", (float)10.0);

        e.Graphics.MeasureString(stringToPrint, txtMain.Font, e.MarginBounds.Size, StringFormat.GenericTypographic, out charPag, out linPag);
        e.Graphics.DrawString(stringToPrint, txtMain.Font, new SolidBrush(Color.Black), e.MarginBounds, StringFormat.GenericTypographic);
        stringToPrint = stringToPrint.Substring(charPag);

        e.Graphics.DrawLine(Pens.Black, e.MarginBounds.Left, e.MarginBounds.Bottom, e.MarginBounds.Right, e.MarginBounds.Bottom);
        e.Graphics.DrawString(numPag.ToString(), rodFont, Brushes.Black, e.MarginBounds.Right - (numPag.ToString().Length * rodFont.SizeInPoints), e.MarginBounds.Bottom + 5);
        if (stringToPrint.Length > 0)
        {
            e.HasMorePages = true;
            numPag++;
        }

【问题讨论】:

  • 为什么要重新发明已经存在并免费提供的东西?在您的应用程序中使用 Scintilla.NET 作为 textArea...scintillanet.codeplex.com
  • 因为是上学的,必须自己动手。(可惜)
  • 呃,等等,你是在寻求帮助自己做吗?使用 [homework] 标签。

标签: c# printing colors margin


【解决方案1】:

创建一个保存保留字的HashSet

public HashSet<string> _reservedWords = 
    new HashSet { "if", "else", "class", "..." };

然后您必须找到包含在文本行中的标识符。标识符是以字母或下划线开头并由字母、下划线和数字组成的字符序列。

找到标识符后,检查它是否是保留关键字

bool reserved = _reservedWords.Contains(word);

【讨论】:

  • 问题是如何找到标识符。我正在使用 split(' ') 但如果此人引入 2 个或更多空格,则它只会读取为 1。我的解释对吗?
  • 您可以使用字符串拆分选项来指定它,s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  • 如果字符串可以包含标点符号和其他特殊字符,您可以使用正则表达式查找单词,var matches = Regex.Matches(s, @"\w+");foreach (Match match in matches) { ...}。匹配会告诉您单词的位置 (match.Index) 和长度 (match.Length) 以及单词本身 (match.Value)。
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多