【问题标题】:convert comment in input string into uppercase将输入字符串中的注释转换为大写
【发布时间】:2013-09-13 21:28:44
【问题描述】:

我如何识别用户输入的注释字符串。假设用户输入了

> I am /*not working*/ right now.

所以我想将注释的子字符串> /* not working*/ 转换为大写。我怎么能在 c# 中做到这一点。转换不是问题。问题是如何识别cmets?在 if 块中做什么?

   static void comment(string exp_string)
    {
        for (int i = 0; i < exp_string.Length; i++)
        {
            if (exp_string[i] == 47 && exp_string[i + 1] == 42)

        }

    }

【问题讨论】:

    标签: c# substring uppercase


    【解决方案1】:

    你可以使用这个方法:

    public static string CommentToUpper(string input)
    {
        int index = input.IndexOf("/*");
        if (index >= 0)
        {
            int endIndex = input.LastIndexOf("*/");
            if (endIndex > index)
                return string.Format("{0}/*{1}*/{2}", 
                    input.Substring(0, index), 
                    input.Substring(index + 2, endIndex - index - 2).ToUpper(), 
                    input.Substring(endIndex + 2));
            else
                return string.Format("{0}/*{1}", 
                    input.Substring(0, index), 
                    input.Substring(index + 2).ToUpper());
        }
        return input;
    }
    

    这样使用:

    string output =  CommentToUpper("> I am /*not working*/ right now.");
    Console.Write(output);
    

    Demo

    【讨论】:

    • 新手,为什么 SubstringIndexOf 被允许但 Regex 不允许?
    • 那是因为我正在学习设计编译器,我被要求使用 switch 或 if else 结构来匹配字符串与我的正则表达式
    【解决方案2】:

    如果您被限制使用像正则表达式这样干净的东西,请考虑使用 String.SubString()String.ToUpper()

    我认为你受到限制很愚蠢,但有时别无选择。祝你好运。

    编辑:要考虑的另一件事是使用 IndexOf()。不过,我把它留给你,在 MSDN 中找到

    【讨论】:

    • 谢谢。这真的很有帮助
    • -1 I think it's silly, “你为什么要学数学,你不会成为数学家”
    • @I4V 限制访问可能有充分的理由;除了“不能那样做”之外,几乎没有提供任何解释,所以随意限制恕我直言感觉很愚蠢。
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2018-09-16
    • 2010-10-18
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多