文字列、char、書式設定
Coddyの「Python開発者のためのC#」コースのレッスン 5/48。
Pythonのstrip/upperとf文字列は、Trim/ToUpperInvariantとドル記号を接頭辞に付けた補間文字列に相当します。Pythonには独立したchar型がありません。C#では、シングルクォートで囲まれた文字はダブルクォートで囲まれた文字列とは異なります。文字列のインデックス指定とUnicodeの詳細は同一ではないため、フィクスチャではASCIIを使用します。
文字列は不変です。TrimとToUpperInvariantは元の文字列を変更するのではなく、新しい文字列を返します。charでは1文字をシングルクォートで囲み、stringではダブルクォートを使用します。補間文字列ではドル記号を接頭辞に付け、波括弧を使用します。マシン間で出力を安定させる必要がある場合は、不変カルチャの大文字小文字変換と書式設定を使用します。
Pythonの参照例
name = " pen "
print(f"{name.strip().upper()}:{2}")Main内のC#の文
string name = " pen ";
Console.WriteLine($"{name.Trim().ToUpperInvariant()}:{2}");これらは学習内容に焦点を当てた抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットでは関連する宣言と文を示しています。
参照出力:
PEN:2C#の出力:
PEN:2チャレンジ
簡単入力はASCIIの名前の行と整数の個数の行です。前後の空白を取り除いて大文字にした名前、コロン、続いて個数を返してください。内部の空白はそのままにしてください。
ロック解除されている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);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Python開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ