文字列、char、書式設定
Coddyの「R開発者のためのC#」コースのレッスン 5/48。
Rのtrimws、toupper、sprintfは、Trim、ToUpperInvariant、ドル記号を前置する補間文字列に相当します。Rには1文字用の文字型はありません。'A'と"A"は、どちらも長さ1の文字ベクトルです。C#では、シングルクォートはcharを、ダブルクォートはstringを表します。Rは文字数を数える一方、C#の文字列の長さはUTF-16コード単位で数えるため、フィクスチャではASCIIを使用します。
文字列は不変です。TrimとToUpperInvariantは、元の文字列を変更するのではなく、新しい文字列を返します。charでは文字をシングルクォートで囲み、stringではダブルクォートで囲みます。補間文字列では、ドル記号を前置し、中括弧を使用します。マシン間で出力を一定にする必要がある場合は、不変カルチャで大文字小文字の変換と書式設定を行います。
Rの参考コード
name <- " pen "
cat(sprintf("%s:%d\n", toupper(trimws(name)), 2L))Main内のC#ステートメント
string name = " pen ";
Console.WriteLine($"{name.Trim().ToUpperInvariant()}:{2}");これらは、特定の内容に焦点を当てた教材用の抜粋です。課題ファイルには、実行可能な完全なラッパーが含まれています。上記のスニペットは、関連する宣言とステートメントを示しています。
参考出力:
PEN:2C#の出力:
PEN:2チャレンジ
簡単入力は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);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
R開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ