字符串、char 与格式化
Coddy 面向 C++ 开发者的 C# 课程的第 5 课,共 48 课。
C++ 的 std::string 可变,其 char 元素是窄代码单元;C# 字符串不可变,是 UTF-16 序列,并且 char 与 string 是不同的类型。C# 的 Trim 和 ToUpperInvariant 会返回新文本。为了确保 C++ 大小写转换安全,比较使用 ASCII,并显式转换为 unsigned char。
字符串不可变。Trim 和 ToUpperInvariant 会返回新字符串,而不是修改原字符串。表示字符时,char 使用单引号;string 使用双引号。插值字符串以美元符号为前缀,并使用花括号。当输出必须在不同机器上保持稳定时,请使用不变的大小写转换和格式设置。
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:2C# 输出:
PEN:2挑战
简单输入包括一行 ASCII 名称和一行整数计数。返回去除首尾空格并转为大写的名称、一个冒号,然后是计数。保留名称内部的空格。
编辑未锁定的 C# 文件。可见的已锁定文件 Main.cs 会读取上述行,调用 Exercise.Solve,验证输入未被修改,并在结果末尾输出一个换行符。保留声明的 API。不要添加第二个 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器