簡體   English   中英

將字符轉換為 ASCII 符號

[英]Converting char to ASCII symbol

所以我想制作“hello world”。 以一種創造性的方式,我想出了使用 ASCII 的想法,但我現在不知道如何將 char 轉換為 ASCII 符號(既不是來自字符串): 這是我的代碼:

public static void Main()
{
    List<string> imie = new List<string>();

    greet();
}
public static string greet()
{
    string s = "";
    string nums = "104 101 108 108 111 32 119 111 114 108 100 33";
    char[] numbers = nums.ToCharArray();
    foreach (char l in numbers)
    {
        s += Encoding.ASCII.GetChars(new byte[] {l});
    }

    return s;
}

同樣在行“s += Encoding.ASCII.GetChars(new byte[] {l});” 我收到錯誤消息“無法將類型‘char’隱式轉換為‘byte’。存在顯式轉換(是否缺少強制轉換?)”

給你 go

   public static string greet() {
        string s = "";
        string nums = "104 101 108 108 111 32 119 111 114 108 100 33";
        var numbers = nums.Split(" ");
        foreach (var nstr in numbers) {
            int k = Int32.Parse(nstr);
            s += Convert.ToChar(k);

        }

        return s;
    }

或更好(附加到一個字符串是非常低效的)

  public static string greet() {
        StringBuilder s = "";
        string nums = "104 101 108 108 111 32 119 111 114 108 100 33";
        var numbers = nums.Split(" ");
        foreach (var nstr in numbers) {
            int k = Int32.Parse(nstr);
            s.Append(Convert.ToChar(k));

        }

        return s.ToString();
    }

挺有創意的,不過好像創意水平還跟不上你C#的知識水平。。。誤區很多,讓這個問題回答起來有點吃力。

讓我們從Main()方法開始:

  1. 你不使用變量

    List<string> imie = new List<string>();

    但實際上,這種類型的列表在程序的不同地方很有用。 現在,讓我們將這行代碼放在greet()方法中。

  2. 你調用greet()返回一個字符串,但你從不使用返回值。 讓我們用打印語句包圍它:

     Console.WriteLine(greet());

Main() 方法現在看起來像

public static void Main()
{   
    Console.WriteLine(greet());
}

讓我們 go 繼續使用greet()方法。

  1. 變量s的描述性不強。 讓我們將它重命名為helloworld ,以便您更好地了解它的用途。

  2. 我們不使用單個字符串,而是采用字符串列表的想法。

List<string> numbers = new List<string>{"104", "101", "108", "108", "111", "32", "119", "111", "114", "108", "100", "33"};
  1. 我們現在可以去掉nums和舊的numbers變量。 我們不需要那些。

  2. for循環給你一個string而不是單個字符(實際上是數字的單個數字)。 讓我們也更改變量名稱。

foreach (string number in numbers)

在 for 循環中使用單數和復數是一種很好的做法。

  1. 對於字符串連接,讓我們使用int.Parse()而不是進一步弄亂字符的各個數字。 為了使數字成為字符,我們需要將其轉換為char
helloworld += (char) int.Parse(number);

方法:

public static string greet()
{
    List<string> numbers = new List<string>{"104", "101", "108", "108", "111", "32", "119", "111", "114", "108", "100", "33"};  
    string helloworld = "";
    foreach (string number in numbers)
    {
        helloworld += (char) int.Parse(number);
    }
    return helloworld;
}
public static string greet()
{
    string nums = "104 101 108 108 111 32 119 111 114 108 100 33";
    var bytes = nums.Split().Select(n => byte.Parse(n)).ToArray();
    return Encoding.ASCII.GetChars(bytes);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM