문자열, char와 서식 지정
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 5번째.
C++의 std::string은 변경 가능하며 char 요소는 좁은 코드 단위입니다. C# 문자열은 변경할 수 없는 UTF-16 연속이며 char는 string과 구별됩니다. C#의 Trim과 ToUpperInvariant는 새 텍스트를 반환합니다. 비교에서는 ASCII를 사용하고, C++에서 대소문자 변환을 안전하게 처리하기 위해 명시적으로 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# 컴파일러