1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#のstring型は配列のように扱える?VBAとの違いから理解する文字列操作の基本

Last updated at Posted at 2025-10-19

C#のstring型は配列のように扱える?VBAとの違いから理解する文字列操作の基本

はじめに

C#でAtCoderに挑戦していると、文字列の扱いが非常に柔軟で便利だと感じることがあります。特に string 型が「配列のように振る舞う」点は、VBAに慣れた方にとっては驚きかもしれません。

本記事では、C#の string 型の基本的な性質を、VBAとの比較を交えながら解説します。業務でVBAを使っている方が、AtCoderやC#にスムーズに移行できるような視点を意識しています。


1. C#のstring型は配列のように扱える

インデックスアクセスが可能

string s = "abc";
Console.WriteLine(s[0]); // a
Console.WriteLine(s[1]); // b
Console.WriteLine(s[2]); // c
  • s[i]char 型の文字が取得できる
  • Length プロパティで文字数も取得可能

foreachで文字列を走査できる

foreach (char c in s)
{
    Console.WriteLine(c);
}
  • 配列と同じように、文字列の各文字を順に処理できる

2. VBAの文字列操作との違い

VBAではMid関数やループが基本

Dim s As String
s = "abc"

Dim i As Integer
For i = 1 To Len(s)
    Debug.Print Mid(s, i, 1)
Next i
  • VBAでは文字列のインデックスは 1始まり
  • Mid(s, i, 1) で1文字ずつ取得
  • Len(s) で文字数を取得

VBAでは配列的アクセスは不可

' VBAでは s(0) のようなアクセスはできない
' s(1) は Variant の配列でない限りエラーになる

3. イミュータブルの違い

C#のstringは変更不可(イミュータブル)

string s = "abc";
// s[0] = 'x'; // コンパイルエラー
  • 文字列の一部を変更するには、新しい文字列を作る必要がある

VBAも基本的には再代入で対応

Dim s As String
s = "abc"
s = "xbc" ' 文字列全体を再代入
  • VBAでも文字列の一部変更は Mid 関数や Replace 関数を使う

4. 実務と競技プログラミングでの使い分け

観点 VBA C#
文字列の走査 Mid + For s[i] または foreach
文字数取得 Len(s) s.Length
文字列変更 Replace, Mid Substring, Replace, new string
配列的アクセス 不可 可能(s[i]
文字列は変更可能? 再代入で対応 イミュータブル(変更不可)

5. まとめ

  • C#の string 型は、配列のようにインデックスアクセスが可能で、文字列処理が非常に柔軟
  • VBAでは MidLen を使った明示的な処理が必要
  • 両者の違いを理解することで、業務と競技プログラミングの両方で効率的な文字列操作が可能になる

おまけ:AtCoder ABC081AをC#とVBAで比較

C#版

string s = Console.ReadLine();
int count = 0;
for (int i = 0; i < 3; i++)
{
    if (s[i] == '1') count++;
}
Console.WriteLine(count);

VBA版(標準入力を模擬)

Dim s As String
s = "101" ' 仮入力

Dim i As Integer, count As Integer
count = 0
For i = 1 To Len(s)
    If Mid(s, i, 1) = "1" Then count = count + 1
Next i

Debug.Print count
1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?