Menu
CoddyTech

文字列、char、書式設定

Coddyの「C++開発者のためのC#」コースのレッスン 5/48。

C++のstd::stringは変更可能で、そのchar要素は狭いコード単位です。C#の文字列は不変のUTF-16シーケンスであり、charはstringとは異なります。C#のTrimとToUpperInvariantは新しいテキストを返します。比較ではASCIIを使用し、C++で大文字小文字変換を安全に行うため、明示的にunsigned charへ変換します。

文字列は不変です。TrimとToUpperInvariantは元の文字列を変更するのではなく、新しい文字列を返します。文字にはシングルクォートを使い、文字列にはダブルクォートを使います。補間文字列にはドル記号の接頭辞と波括弧を使います。出力をマシン間で安定させる必要がある場合は、カルチャに依存しない大文字小文字変換と書式設定を使用します。

C++の参考コード

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
string name = "  pen ";
name.erase(0,name.find_first_not_of(" ")); name.erase(name.find_last_not_of(" ")+1);
transform(name.begin(),name.end(),name.begin(),[](unsigned char c){ return static_cast<char>(toupper(c)); });
cout << name << ":2\n";
}

Main内のC#文

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

これらは要点を絞った解説用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットでは関連する宣言と文を示しています。

参考出力:

PEN:2

C#の出力:

PEN:2
challenge icon

チャレンジ

簡単

入力は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);
}
}
quiz icon腕試し

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

C++開発者のためのC#のすべてのレッスン

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