技術頻道導航
HTML/CSS
.NET技術
IIS技術
PHP技術
Js/JQuery
Photoshop
Fireworks
服務器技術
操作系統
網站運營

贊助商

分類目錄

贊助商

最新文章

搜索

【兩示例演示】C#如何把八進制字符串轉換為整數

作者:admin    時間:2022-5-27 18:18:3    瀏覽:

在前文中我們介紹了C#將二進制字符串轉換為整數的方法,在本文中,我們將通過兩個示例來介紹C#是如何把八進制字符串轉換為整數的。

示例

要將八進制字符串轉換為整數,我們必須使用Convert.ToInt32()函數來轉換值。

示例1:

using System;
using System.Text;
  
class Prog {
  
    static void Main(string[] args)
    {
        string[] str = { "121", "202", "003" };
        int num1 = 0;
        try {
  
            foreach(string item in str)
            {
                num1 = Convert.ToInt32(item, 8);
                Console.WriteLine(num1);
            }
        }
        catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        }
    }
}

輸出

81
130
3

示例2:

using System;
using System.Text;
  
namespace webkaka {
  
class Prog {
  
    static void Main(string[] args)
    {
        string[] str = { "111", "543", "333", "607", "700" };
        int num2 = 0;
        try {
  
            foreach(string item in str)
            {
                num2 = Convert.ToInt32(item, 8);
                Console.WriteLine(num2);
            }
        }
        catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        }
    }
}
}

輸出

73
355
219
391
448

Convert.ToInt32(String) 知識擴展

ToInt32(String)

將數字的指定字符串表示形式轉換為等效的 32 位有符號整數。

public static int ToInt32 (string? value);

參數

value String:包含要轉換的數字的字符串。

返回

 Int32:一個 32 位有符號整數,等效于 中的數字,如果是value,則為 0(零)。valuenull

例外

  • FormatException :value 不包含可選符號后跟數字序列(0 到 9)。
  • OverflowException:value 表示小于MinValue或大于MaxValue的數字。

例子

以下示例嘗試將數字字符串數組中的每個元素轉換為整數。

string[] values = { "One", "1.34e28", "-26.87", "-18", "-6.00",
                    " 0", "137", "1601.9", Int32.MaxValue.ToString() };
int result;

foreach (string value in values)
{
   try {
      result = Convert.ToInt32(value);
      Console.WriteLine("轉換 {0} 數字 '{1}' 到 {2} 數值 {3}.",
                        value.GetType().Name, value, result.GetType().Name, result);
   }
   catch (OverflowException) {
      Console.WriteLine("{0} 超出Int32類型的范圍.", value);
   }
   catch (FormatException) {
      Console.WriteLine("{0} 數值 '{1}' 的格式不可識別.",
                        value.GetType().Name, value);
   }
}
// 輸出:
// String 數值 'One' 的格式不可識別.
// String 數值 '1.34e28' 的格式不可識別.
// String 數值 '-26.87' 的格式不可識別.
// 轉換 String 數字 '-18' 到 Int32 數值 -18.
// String 數值 '-6.00' 的格式不可識別.

// 轉換 String 數字 ' 0' 到 Int32 數值 0.
// 轉換 String 數字 '137' 到 Int32 數值 137.
// String 數值 '1601.9' 的格式不可識別.
// 轉換 String 數字 '2147483647' 到 Int32 數值 2147483647.

評論

使用ToInt32(String)方法等效于傳遞valueInt32.Parse(String)方法。value通過使用當前文化的格式約定來解釋。

如果你不想在轉換失敗時處理異常,則可以調用Int32.TryParse方法。它返回一個布爾值,指示轉換是成功還是失敗。參考以下文章:

總結

本文通過兩個示例,介紹了C#是如何把八進制字符串轉換為整數的。通過本文的學習,我們了解了Convert.ToInt32()函數的更多實用功能作用。

相關文章

x
  • 站長推薦
/* 左側顯示文章內容目錄 */