文字列型 (string型) を利用する - C#
文字列型 (string型) を利用するコードを紹介します。
概要
C#では文字列を格納する型としてstring型が利用できます。この記事では string型の定義や利用について紹介します。
書式:文字列の宣言
文字列の宣言はstring型の変数を宣言するコードでできます。
記述例
Form1_Loadメソッドで text という名称のstring型変数を宣言します。
using System;
using System.Windows.Forms;
namespace StringSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string text;
}
}
}
書式:文字列の代入
文字列への代入は変数の代入と同じ処理で可能です。
記述例
Form1_Loadメソッドで text という名称のstring型変数を宣言した後に、「ペンギン」という文字列値を代入します。
using System;
using System.Windows.Forms;
namespace StringSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string text;
text = "ペンギン";
}
}
}
書式:文字列の参照
文字列の参照は変数名を記述します。
記述例
Form1_Loadメソッドで text という名称のstring型変数を宣言した後に、「ペンギン」という文字列値を代入します。
using System;
using System.Windows.Forms;
namespace StringSimple
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string text;
text = "ペンギン";
MessageBox.Show(text);
}
}
}
プログラム例
UI
下図のUIを作成します。フォームにButtonコントロールを一つ配置します。
コード
Windowsフォームアプリケーションを作成し、下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StringSimple
{
public partial class FormMessage : Form
{
public FormMessage()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
string text;
text = "ペンギン";
MessageBox.Show(text);
}
}
}
解説
ボタンをクリックすると、下記のコードが実行されます。最初の行で text という名前のstring型の変数を宣言します。2番目の行で宣言したtext変数に"ペンギン"の文字列の値を代入します。3行目でメッセージボックスを表示します。Showメソッドの引数にはメッセージボックスに表示する文字列を与えます。text変数名を記述することで、text変数に代入されている値をメッセージボックスに表示します。今回の場合text変数には「ペンギン」の文字列が代入されているため、メッセージボックスに「ペンギン」の文字列が表示されます。
string text;
text = "ペンギン";
MessageBox.Show(text);
実行結果
プロジェクトを実行します。下図のウィンドウが表示されます。ウィンドウのボタンをクリックします。
ボタンをクリックするとメッセージボックスが表示されます。メッセージに「ペンギン」の文字列が表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用