|
|
|
|
|
在前文中我們介紹了C#將二進制字符串轉換為整數(shù)的方法,在本文中,我們將通過兩個示例來介紹C#是如何把八進制字符串轉換為整數(shù)的。
示例
要將八進制字符串轉換為整數(shù),我們必須使用Convert.ToInt32()
函數(shù)來轉換值。
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
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) 知識擴展
將數(shù)字的指定字符串表示形式轉換為等效的 32 位有符號整數(shù)。
public static int ToInt32 (string? value);
value
String:包含要轉換的數(shù)字的字符串。
Int32
:一個 32 位有符號整數(shù),等效于 中的數(shù)字,如果是value,則為 0(零)。valuenull
value
不包含可選符號后跟數(shù)字序列(0 到 9)。value
表示小于MinValue或大于MaxValue的數(shù)字。以下示例嘗試將數(shù)字字符串數(shù)組中的每個元素轉換為整數(shù)。
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} 數(shù)字 '{1}' 到 {2} 數(shù)值 {3}.",
value.GetType().Name, value, result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("{0} 超出Int32類型的范圍.", value);
}
catch (FormatException) {
Console.WriteLine("{0} 數(shù)值 '{1}' 的格式不可識別.",
value.GetType().Name, value);
}
}
// 輸出:
// String 數(shù)值 'One' 的格式不可識別.
// String 數(shù)值 '1.34e28' 的格式不可識別.
// String 數(shù)值 '-26.87' 的格式不可識別.
// 轉換 String 數(shù)字 '-18' 到 Int32 數(shù)值 -18.
// String 數(shù)值 '-6.00' 的格式不可識別.
// 轉換 String 數(shù)字 ' 0' 到 Int32 數(shù)值 0.
// 轉換 String 數(shù)字 '137' 到 Int32 數(shù)值 137.
// String 數(shù)值 '1601.9' 的格式不可識別.
// 轉換 String 數(shù)字 '2147483647' 到 Int32 數(shù)值 2147483647.
使用ToInt32(String)
方法等效于傳遞value
給Int32.Parse(String)
方法。value
通過使用當前文化的格式約定來解釋。
如果你不想在轉換失敗時處理異常,則可以調(diào)用Int32.TryParse
方法。它返回一個布爾值,指示轉換是成功還是失敗。參考以下文章:
總結
本文通過兩個示例,介紹了C#是如何把八進制字符串轉換為整數(shù)的。通過本文的學習,我們了解了Convert.ToInt32()
函數(shù)的更多實用功能作用。
相關文章