2
0

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#】競プロ入出力メモ

Last updated at Posted at 2023-09-17

C#での入力の受け取りは基本的に1行ごとに受け取って格納していく。

・1行に1つだけの値を受け取る

Console.ReadLine()でstring型文字列として一行受け取り、それを数値や文字に変換する。

// 文字列
string s = Console.ReadLine();
// 数値
int n = int.Parse(Console.ReadLine());
// 文字
char ch = (char)Console.Read();

・1行に空白区切りで複数与えられる値を受け取る

1行の入力を受け取り、Split(' ')を用いて空白で区切って配列として格納する。それを(他の型に変換しながら)配列のインデックス順に変数に格納していく。

// 文字列
string[] input = Console.ReadLine().Split(' ');
string s = input[0];
string t = input[1];
// 数値
string[] input = Console.ReadLine().Split(' ');
int n = int.Parse(input[0]);
int m = int.Parse(input[1]);
// 文字
string[] input = Console.ReadLine().Split(' ');
// C#ではString型文字列はchar型文字の配列として扱える
char ch1 = input[0][0]; 
char ch2 = input[1][0];

・1行に空白区切りで複数与えられる値を配列として受け取る

空白で区切られたstring型配列を他の型に変換して格納する。

// 文字列
string[] strArr = Console.ReadLine().Split(' ');
// 数値
int[] numArr = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
// 文字
char[] chArr = Array.ConvertAll(Console.ReadLine().Split(' '), item => item[0]);

・h行w列の2次元配列として受け取る

1行の文字列をchar型配列として受け取る .ToCharArray()を使う。

// 1行の文字列をchar型配列として受け取る
char[] chArray = Console.ReadLine().ToCharArray();

・文字の場合
例:
...
#.#
..#

int h; // 行数
int w; // 列数
char[,] map = new char[h, w];
for (int i = 0; i < h; i++)
{
    char[] input = Console.ReadLine().ToCharArray();
    for (int j = 0; j < w; j++)
    {
        map[i, j] = input[j];
    }
 }

・数値の場合
例:
123
456
789

int h; // 行数
int w; // 列数
int[,] map = new int[h, w];
for (int i = 0; i < h; i++)
{
    char[] input = Console.ReadLine().ToCharArray();
    for (int j = 0; j < w; j++)
    {
        // 各文字を整数に変換
        map[i, j] = input[j] - '0';
    }
 }

・1行に1つの値を出力

文字列/数値/文字問わず出力可能。

int num = 123;
Console.WriteLine(num);
// Output: 123

・1行に複数の値を出力

複合書式。Console.WriteLine()関数の第二引数以降の変数がそれぞれ0番目,1番目...となり第一引数の{0},{1}...に対応する。存在しない引数の番号を指定するとエラーとなる。

int num = 123;
string str = "abc";
char ch = 'あ';
Console.WriteLine("{0}, {2}, {1}", num, str, ch);
// Output: 123, あ, abc

【最後に】

今後も自分が役に立ったリファレンスやテクニックについて随時追記していこうと思います。
もし誤字脱字および技術的なご指摘がございましたらお気軽にコメントください。

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?