.NET ヘルプ

C#で文字列を整数に解析する方法(開発者向けの仕組み)

データ型の変換はプログラミングの基本的な概念であり、C#でプログラミングする際には、数値の文字列表現を整数に変換することが最も一般的なタスクのひとつです。 このプロセスは、ユーザー入力や外部ソースからのデータを計算やその他の操作のために数値フォーマットに変換する必要がある多くのアプリケーションで役立ちます。

このチュートリアルでは、C#によって提供されるさまざまな文字列を整数に変換する方法を探ります。 また、IronPDFライブラリのホームページも探索します。

文字列変数を整数に変換する基本

Convert.ToInt32 メソッドと Int32.Parse メソッドは、文字列値を整数値に変換するための C# の標準ツールです。 これらの関数は、入力された文字列の数値を解釈し、それを整数(int)に変換するように設計されています。 しかし、これらのメソッドは文字列が正しい形式でない場合に例外をスローする可能性があるため、これらのツールを使用する際には例外処理が不可欠な要素となります。

Int32.Parse メソッドを使用する

Int32.Parse メソッドは、有効な数値文字列を直接整数に変換します。 有効な数値形式で文字列が必要です。 そうしないと、FormatException がスローされます。 このメソッドは、文字列が有効な数値であることが確かである場合には簡単です。 例えば:

public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
public static string inputString = "123";
public static int result = int.Parse(inputString);
Console.WriteLine(result);
Public Shared inputString As String = "123"
Public Shared result As Integer = Integer.Parse(inputString)
Console.WriteLine(result)
$vbLabelText   $csharpLabel

上記のコードでは、inputStringに有効な数値が含まれており、Parseメソッドはそれを整数の123に変換します。しかし、inputStringが数値以外の文字を含んでいるか、または空の文字列である場合、Parseを使用するとFormatExceptionArgumentNullExceptionが発生します。

Convert.ToInt32 メソッドを使用する

文字列を整数に変換するための別の変換クラスはConvert.ToInt32です。 このメソッドはInt32.Parseに似ていますが、もう少し柔軟性を提供します。 C#で文字列を整数に変換する方法を効果的に理解することは、データ操作の多くの可能性を開き、堅牢なアプリケーションのパフォーマンスを保証します。 null や空の文字列を扱う際に、例外をスローすることを避けるためにデフォルト値のゼロを返します。 以下のように使用できます:

public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
public static string inputString = null;
public static int result = Convert.ToInt32(inputString);
Console.WriteLine(result);
Public Shared inputString As String = Nothing
Public Shared result As Integer = Convert.ToInt32(inputString)
Console.WriteLine(result)
$vbLabelText   $csharpLabel

このメソッドはinputStringを例外を発生させずに0に変換するため、正しく初期化されていない変数に対しても安全です。

Int32.TryParseの高度な技術

変換プロセスをより良く制御するために、特に信頼できない可能性のあるユーザー入力を扱う場合、Int32.TryParse は推奨される方法です。 このメソッドは数値文字列の解析を試み、文字列を整数に変換するのにTryParseメソッドが成功したかどうかを示すブール値を返します。 変換された整数を返すために out パラメーターを使用します。

Int32.TryParseの使用例

次のようにして、Int32.TryParse メソッドを使用し、文字列入力を整数値に安全に変換し、無効な文字列入力を上手に処理することができます:

string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
string inputString = "abc123";
int num;
bool conversionSucceeded = int.TryParse(inputString, out num);
if (conversionSucceeded)
{
    Console.WriteLine("Successfully parsed: " + num);
}
else
{
    Console.WriteLine("Conversion failed. Provided string is not a valid integer.");
}
Dim inputString As String = "abc123"
Dim num As Integer = Nothing
Dim conversionSucceeded As Boolean = Integer.TryParse(inputString, num)
If conversionSucceeded Then
	Console.WriteLine("Successfully parsed: " & num)
Else
	Console.WriteLine("Conversion failed. Provided string is not a valid integer.")
End If
$vbLabelText   $csharpLabel

この例では、Int32.TryParseinputString が有効な整数ではないため false を返します。 out パラメーター num0 のままで、プログラムは例外をスローすることなく変換の失敗をユーザーに通知します。

IronPDFライブラリの紹介

IronPDF 概要セクションは、.NET フレームワークを使用する開発者向けにPDF操作を簡素化するために設計された強力なC#ライブラリです。 HTML、CSS、JavaScript、および画像から直接PDFドキュメントの作成、編集、管理を可能にします。 IronPDFの主な機能は、HTMLコンテンツを直接PDFに変換する能力です。

これには、ウェブページ全体やHTML文字列を変換することが含まれており、非常に柔軟性があります。 IronPDFは、パワフルでかつ統合しやすいように設計されており、さまざまな開発環境をサポートしています。

コード例

以下は、文字列を整数に解析し、PDF内に表示するC#コードでPDF生成を行うIronPDFを組み合わせた簡単な例です。 この例では、数値文字列を取得し、それを整数に変換した後、IronPDF を使用して PDF ドキュメントに整数を印刷することを想定しています。

using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
using IronPdf;
using System;
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "Your-License-Key";
        // Create a new PDF document
        var pdf = new ChromePdfRenderer();
        // Sample string that represents an integer
        string numberString = "12345";
        // Parse the string into an integer
        int number;
        bool result = Int32.TryParse(numberString, out number);
        if (result)
        {
            // Create HTML content including the parsed number
            string htmlContent = $"<h1>The number is: {number}</h1>";
            // Generate a PDF from the HTML string
            var document = pdf.RenderHtmlAsPdf(htmlContent);
            // Save the PDF to a file
            document.SaveAs("Output.pdf");
            Console.WriteLine("PDF generated successfully with the number included.");
        }
        else
        {
            Console.WriteLine("The string could not be parsed into an integer.");
        }
    }
}
Imports IronPdf
Imports System
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "Your-License-Key"
		' Create a new PDF document
		Dim pdf = New ChromePdfRenderer()
		' Sample string that represents an integer
		Dim numberString As String = "12345"
		' Parse the string into an integer
		Dim number As Integer = Nothing
		Dim result As Boolean = Int32.TryParse(numberString, number)
		If result Then
			' Create HTML content including the parsed number
			Dim htmlContent As String = $"<h1>The number is: {number}</h1>"
			' Generate a PDF from the HTML string
			Dim document = pdf.RenderHtmlAsPdf(htmlContent)
			' Save the PDF to a file
			document.SaveAs("Output.pdf")
			Console.WriteLine("PDF generated successfully with the number included.")
		Else
			Console.WriteLine("The string could not be parsed into an integer.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

C#で文字列を整数に変換する (開発者のための方法): 図1 - 前述のコード例から出力されたPDF

結論

文字列を整数に変換することは、特にユーザーや外部ソースからのデータ入力を処理するときに、C#プログラミングにおいて一般的な要件です。 Int32.ParseConvert.ToInt32、および TryParse メソッドの違いを理解することは、堅牢でエラーに強いコードを書くために不可欠です。

これらのメソッドを効果的に使用することで、アプリケーションがさまざまな入力フォーマットに対応し、無効なデータに対しても優雅に反応することができます。 IronPDFの無料試用ライセンスを探索することで、購入を決定する前にその機能を試すことができます。 IronPDFを長期的にプロジェクトに統合したいと考えている方には、IronPDFのライセンスオプションが$749から始まります。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
Rebus .NET Coreの例(開発者向けの仕組み)
次へ >
C# ベースコンストラクター呼び出し(開発者向けの動作方法)