簡體   English   中英

如何在 C# 中將 char 數組的內容轉換為其相應的整數值?

[英]How do I convert the contents of a char array to their corresponding integer values in C#?

我正在獲取用戶提供的字符串,並通過執行以下操作將其轉換為字符數組。

string userInput = Console.ReadLine();
char[] charArray = userInput.ToCharArray();

從那里我想遍歷整個 char 數組並將每個索引轉換為其相應的整數值,但這就是我遇到麻煩的地方。

如果我的字符串是"Hello World" ,我的字符數組應該是這樣的

{'H', 'e', 'l', 'l', 'o', '', 'W', 'o', 'r', 'l', 'd'}

然后 int 數組看起來像這樣

{72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100}

這是我編寫的用於遍歷 char 數組的循環:

for (int count = 0; count<charArray.Length; count++)
        {
            myInt = charArray[count]; 
        }

使用這個循環,我知道myInt的值myInt繼續改變,直到循環終止。 含義的價值myInt將對應的最后一個索引的int值charArray 我也試過使用charArray[count] =... ,但我不知道如何正確使用它。 任何見解將不勝感激。

你已經差不多完成了,但你可以考慮以下幾點:

  • 結果將存儲在哪里?

如果您有 X 個 CHARS 的數組,則必須制作一個長度相同的 INT 數組。

int[] intArray=new int[charArray.Length];

然后你可以將每個元素分配給相應的“框”

for (int count = 0; count<charArray.Length; count++)
{
    intArray[count]= (int)charArray[count]; 
}

您可能希望將 char 強制轉換為 int(其中包含類型的括號稱為強制轉換,您可以在其中將一種類型的變量轉換為另一種類型,只要有可能)

using System;

namespace MyApplication {

  class Program    {
    static void Main(string[] args) 
    {
      char[] A = {'1', '2', '3', '4'};

        int[] Aint = Array.ConvertAll(A, c => (int)Char.GetNumericValue(c));
        for (int i = 0;i < Aint.Length;i++)
        {
              Console.WriteLine(Aint[i]);
        }
    } 
  } 
}

在這種情況下,輸出將是 1 2 3 4

要獲取字符的 int,您可以執行 myInt = (int)(charArray[count] - '0');

暫無
暫無

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

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