Menu
CoddyTech

文字列、char、書式設定

Coddyの「GDScript開発者向けC#」コースのレッスン 5/48。

GDScriptのstrip_edges、to_upper、%書式演算子は、Trim、ToUpperInvariant、ドル記号を前置する補間文字列に対応します。GDScriptにはchar型がなく、'A'と"A"を同じStringとして扱います。C#では、シングルクォートはcharを、ダブルクォートはstringを作ります。GDScriptの文字列はUnicodeコードポイントでインデックス付けされる一方、C#の文字列はUTF-16コード単位でインデックス付けされるため、テストデータにはASCIIを使用します。

文字列は不変です。TrimとToUpperInvariantは、元の文字列を変更するのではなく、新しい文字列を返します。charでは文字をシングルクォートで囲み、stringではダブルクォートで囲みます。補間文字列では、ドル記号を前置し、中括弧を使います。出力をどのマシンでも一定にする必要がある場合は、カルチャに依存しない大文字小文字変換と書式設定を使用します。

GDScriptの参照例

extends Node

func _ready() -> void:
    var item := "  pen "
    print("%s:%d" % [item.strip_edges().to_upper(), 2])

Main内のC#文

string item = "  pen ";
Console.WriteLine($"{item.Trim().ToUpperInvariant()}:{2}");

GDScriptの参照例は完全なスクリプトです。C#のスニペットは、要点に絞った教材用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上のスニペットには関連する宣言と文が示されています。

参照出力:

PEN:2

C#の出力:

PEN:2
challenge icon

チャレンジ

簡単

入力はASCII名の行と整数countの行です。前後の空白を取り除いて大文字にした名前、コロン、続いてcountを返します。内部の空白は保持してください。

ロックされていないC#ファイルを編集してください。表示されているロック済みのMain.csは、説明されている行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを検証し、最後に改行を1つ付けて結果を出力します。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を表示したりしないでください。

自分で試してみよう

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

GDScript開発者向けC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ