文字列中で 「"」ダブルクォート、改行、タブを表現するコードを紹介します。
C#での文字列を示すために、文字列を"(ダブルクォーテーション)で囲む必要がありますが、文字列中で「"」や改行コードなどを表現したい場合があります。この記事では文字列中で特殊な文字列を表現するためのコードを紹介します。
エスケープ文字を利用するには文字列中で \ 記号を入力します。主なエスケープ文字は以下があります。また\を記述する際には\\と表現します。
| エスケープ文字列 | 意味 |
|---|---|
| \r | キャリッジリターン |
| \n | ラインフィード (改行) |
| \t | タブ |
| \¥ | "\"文字 |
ダブルクォーテーションを表現する場合は\"を文字列中で入力します。
下図のUIを作成します。フォームにテキストボックスとボタンを配置します。
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 StringBasics
{
public partial class FormEscapeChar : Form
{
public FormEscapeChar()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
string str;
str = "Hello\"C#\"World!";
textBox1.Text = str;
}
}
}
文字列変数に、「"」を含む文字列を代入しています。文字列中での " の表現は \" を記述します。~
プロジェクトを実行します。下図のウィンドウが表示されます。
[button1]をクリックします。テキストボックスに下図のテキスト「Hello"C#"World!」が表示されます。
タブを表現する場合は、文字列中で\tを記述します。
下図のUIを作成します。先のプログラムのUIにボタンを1つ追加したものです。
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 StringBasics
{
public partial class FormEscapeChar : Form
{
public FormEscapeChar()
{
InitializeComponent();
}
private void Button2_Click(object sender, EventArgs e)
{
string str;
str = "ペンギンさん\tホップ!\tステップ\tジャンプ";
textBox1.Text = str;
}
}
}
改行を表現する場合は、文字列中で\nまたは\r\nを記述します。
下図のUIを作成します。フォームに複数行のテキストボックスとボタンを1つ配置したものです。
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 StringBasics
{
public partial class FormLineBreakChar : Form
{
public FormLineBreakChar()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
string str;
str = "ようこそ\r\nC#の\r\n世界へ!";
textBox1.Text = str;
}
}
}
文字列変数にタブを含む文字列を代入しています。タブは \t を文字列に記述することで表現しています。
プロジェクトを実行します。下図のウィンドウが表示されます。
[button2]をクリックします。下図の文字列がテキストボックスに表示されます。文字列が改行されて表示されていることが確認できます。
C#では下記のエスケープ文字が利用できます。
| エスケープ シーケンス | 文字名 | Unicode エンコーディング |
|---|---|---|
| \' | 単一引用符 | 0x0027 |
| \" | 二重引用符 | 0x0022 |
| \\ | 円記号 | 0x005C |
| \0 | Null | 0x0000 |
| \a | 警告 | 0x0007 |
| \b | バックスペース | 0x0008 |
| \f | フォーム フィード | 0x000C |
| \n | 改行 | 0x000A |
| \r | キャリッジ リターン | 0x000D |
| \t | 水平タブ | 0x0009 |
| \U | サロゲート ペアの Unicode エスケープ シーケンス | \Unnnnnnnn |
| \u | Unicode エスケープ シーケンス | \u0041 = "A" |
| \v | 垂直タブ | 0x000B |
| \x | Unicode エスケープ シーケンス | \x0041 または \x41 |