.NET ヘルプ

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

更新済み 6月 6, 2024
共有:

データ型の変換 プログラミングにおいて基礎的な概念です。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)
VB   C#

上記のコードでは、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)
VB   C#

このメソッドは、例外を投げることなく inputString を0に変換するため、適切に初期化されていない可能性のある変数に対してより安全です。

Int32.TryParseを用いた高度な技術

ユーザー入力の信頼性が低い場合など、変換プロセスをより厳密に管理するためには、Int32.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
VB   C#

この例では、Int32.TryParse は false を返します。なぜなら inputString は有効な整数ではないからです。 出力パラメーター num0 のままであり、プログラムは例外をスローすることなく変換の失敗をユーザーに通知します。

IronPDFライブラリの紹介

IronPDF は、.NETフレームワークを使用する開発者のためにPDF操作を簡素化するよう設計された強力なC#ライブラリです。 作成、編集、および管理を可能にします HTMLから直接PDFドキュメントを作成, CSS、JavaScript、および画像。 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
VB   C#

文字列を整数に変換するC#(開発者向けの動作方法):図1 - 前のコード例から生成されたPDF

結論

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

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

< 以前
Rebus .NET Coreの例(開発者向けの仕組み)
次へ >
C# ベースコンストラクター呼び出し(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >