0

我正在尝试用 C# 编写一个行为类似于众所周知的 echo 命令的程序。一切正常,除非我尝试打印带引号的字符串。

例如,在 echo 命令中键入:

echo "Hello, world!"

你得到作为输出:

"Hello, world"

但是当我运行我的程序时,我得到:

Hello, world!

这是代码:

using System;

namespace CSharpEcho
{
    public class Echo
    {
        public static void Main(String[] argv)
        {
            Int32 ArgsLength = argv.Length;

            if(ArgsLength == 0)
                Console.WriteLine("You have to write something!");
            else
            {
                String Str = "";

                foreach(String args in argv)
                {
                    Str += args + " ";
                }

                Console.WriteLine(String.Format("{0}", Str));
            }
        }
    }
}
4

3 回答 3

7

Environment.CommandLine包含确切的命令行内容。

所以你的代码可以是:

public static void Main(String[] argv)
{
  Console.WriteLine(Environment.CommandLine);
}
于 2013-09-15T22:03:18.273 回答
0

字符串中的双引号字符有点棘手。尝试这个:

Console.WriteLine(String.Format(@"""{0}""", Str));

@ 符号使字符串成为字符串文字,这意味着没有“转义”字符。外面的双引号是字符串周围的普通引号,而里面的双引号是实际的引号字符。

于 2013-09-15T22:05:18.617 回答
0

如果您希望输出为“Hello, world”。你可以使用这样的东西:

var text = "\"Hello, World\"";
于 2020-02-19T15:57:29.410 回答