【问题标题】:How to output foreach as a string c# // g prints as an array and not a string如何将 foreach 输出为字符串 c# // g 打印为数组而不是字符串
【发布时间】:2020-09-03 16:50:51
【问题描述】:
byte[] array = Encoding.ASCII.GetBytes(text);

foreach (byte e in array)
{
    int v = e + 1;
    char g = (char)v;
    g.ToString();
    Console.WriteLine(g);
}

当前输出是每行一个字符,但我只想打印一个字符串。

例如,如果text 是“hello”,那么我的输出应该是“ifmmp”。

【问题讨论】:

  • g.ToString(); 单独是“无操作”。 ToString() 返回 一个值,它不会“修改”g 将其转换为字符串。 Console.WriteLine(g.ToString()) 就是你的意思。但是,我不确定它是否符合您的要求。
  • 我试过 Console.WriteLine(g.ToString()) 但它仍然将 g 打印为数组
  • 你能分享你得到的输出和你期望的输出吗?
  • 这个问题需要解决。它缺乏对你想要什么和正在发生的事情的具体描述(即使你可能认为你已经解释了自己,我向你保证你没有),
  • 如果我的输入是“hello”,那么我的输出是“ifmmp”,这是正确的,但它在单独的行上

标签: c# arrays for-loop


【解决方案1】:

我修改了你的代码,它打印 Ifsf!xf!hp 的文本“Here we go”。添加命名空间 System.Text 以编译代码

        byte[] array = Encoding.ASCII.GetBytes(text);

        var sb = new StringBuilder();
        foreach (byte e in array)
        {
            int v = e + 1;
            char g = (char)v;
            sb.Append(g);

        }
        Console.WriteLine(sb.ToString());

【讨论】:

    【解决方案2】:

    使用StringBuilder() 非常有效,但最简单的通用用例解决方案是调用Console.Write() 而不是Console.WriteLine()

    这将导致所有字符串输出附加到同一行,直到调用Console.WriteLine() 或以其他方式写入换行符。它还可以让您轻松地将内容转储到终端进行调试,而无需设置额外的结构来处理该信息流。

    非常清楚,您更新的代码可能是:

    byte[] array = Encoding.ASCII.GetBytes(text);
    
    foreach (byte e in array)
    {
        int v = e + 1;
        char g = (char)v;
        g.ToString();
        Console.Write(g);
    }
    
    // Optional, resets the carriage to the beginning of the next line
    // so that the next output doesn't get appended to the end of the
    // same written string.
    Console.WriteLine();
    

    【讨论】:

      【解决方案3】:

      我建议使用Encoding 类的另一个函数,将字节数组转换为字符串。

      byte[] array = Encoding.ASCII.GetBytes(text);
      for (int index = 0; index < array.Length; index++)
      {
          array[index]++;
      }
      Console.WriteLine(Encoding.ASCII.GetString(array));
      

      【讨论】:

        猜你喜欢
        • 2015-06-02
        • 2011-01-24
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        相关资源
        最近更新 更多