간단한 CSV 구문 분석 패턴
CSV 행을 분석합니다. 단순한 파일에는 기본 Split을 사용하고, 숫자에는 안전한 TryParse를 적용한 다음, 따옴표 안의 쉼표를 처리하는 작은 분할기를 만듭니다.
간단한 CSV 구문 분석 패턴은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.
CSV 파싱 개요
목표: 작은 CSV를 안정적으로 파싱합니다.
- 따옴표가 없는 파일에는 먼저 간단한 Split 사용하기
- 숫자에는 TryParse 사용하기
- 작은 스캐너로 따옴표로 묶인 필드 처리하기
단순 분할(따옴표 없음)
따옴표가 없는 CSV에는 간단한 Split이 작동하며 읽기도 쉽습니다.
using System;
public class Program
{
public static void Main(string[] args)
{
// Simple: no quotes, commas separate fields
string line = "Apple,10,2.5";
string[] parts = line.Split(','); // naive split
Console.WriteLine("Name = " + parts[0]);
Console.WriteLine("Qty = " + parts[1]);
Console.WriteLine("Price= " + parts[2]);
}
}
안전한 숫자 파싱
잘못된 데이터로 인한 충돌을 피하려면 문화권(예: InvariantCulture)을 지정하여 Trim과 TryParse를 사용합니다.
using System;
using System.Globalization;
public class Program
{
public static void Main(string[] args)
{
string line = "Banana, 7, 1.99";
string[] p = line.Split(',');
string name = p[0].Trim();
int qty;
double price;
bool okQty = Int32.TryParse(p[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
bool okPrice = Double.TryParse(p[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);
Console.WriteLine("Parsed: " + name + " | ok=" + (okQty && okPrice) + " -> " + qty + " x " + price);
}
}
단순 분할이 실패하는 이유
따옴표로 묶인 필드에는 쉼표가 포함될 수 있으므로 일반적인 Split을 사용하면 필드가 여러 조각으로 나뉩니다.
using System;
public class Program
{
public static void Main(string[] args)
{
// Name has a comma inside quotes; naive split breaks it
string line = "\"Orange, Blood\",12,3.40";
string[] parts = line.Split(','); // wrong: splits inside the quoted name
Console.WriteLine("Parts found = " + parts.Length); // 4, not 3
foreach (string s in parts) Console.WriteLine("[" + s + "]");
}
}
따옴표를 인식하는 분할
작은 스캐너가 inQuotes를 전환하여 따옴표 안의 쉼표를 무시하며, 두 번 연속된 따옴표("")도 처리합니다.
using System;
using System.Collections.Generic;
using System.Text;
public class Program
{
// Splits a CSV line handling quotes and doubled "" inside quoted fields.
static List<string> SplitCsvLine(string line)
{
List<string> fields = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '\"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
{
// Escaped quote ("") inside a quoted field
sb.Append('\"');
i++; // skip next quote
}
else
{
inQuotes = !inQuotes; // toggle
}
}
else if (c == ',' && !inQuotes)
{
fields.Add(sb.ToString());
sb.Length = 0; // reset
}
else
{
sb.Append(c);
}
}
fields.Add(sb.ToString());
return fields;
}
public static void Main(string[] args)
{
string line = "\"Orange, Blood\",12,\"He said \"\"Hi!\"\"\"";
List<string> parts = SplitCsvLine(line);
Console.WriteLine("Fields = " + parts.Count);
foreach (string f in parts) Console.WriteLine("[" + f + "]");
}
}
CSV에서 객체로
분할 로직을 TryParse 및 최소한의 정리 작업과 결합하여 형식이 지정된 객체를 안전하게 만듭니다.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
public sealed class Product
{
public string Name;
public int Quantity;
public double Price;
}
public class Program
{
static List<string> SplitCsvLine(string line)
{
List<string> fields = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '\"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
{ sb.Append('\"'); i++; }
else { inQuotes = !inQuotes; }
}
else if (c == ',' && !inQuotes)
{ fields.Add(sb.ToString()); sb.Length = 0; }
else
{ sb.Append(c); }
}
fields.Add(sb.ToString());
return fields;
}
static bool TryParseProduct(string line, out Product p)
{
p = null;
List<string> f = SplitCsvLine(line);
if (f.Count < 3) return false;
string name = f[0].Trim().Trim('\"');
int qty;
double price;
bool okQty = Int32.TryParse(f[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
bool okPrice = Double.TryParse(f[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);
if (!okQty || !okPrice) return false;
p = new Product { Name = name, Quantity = qty, Price = price };
return true;
}
public static void Main(string[] args)
{
string[] lines = new string[]
{
"\"Orange, Blood\",12,3.4",
"Apple,10,2.5",
"\"He said \"\"Hi\"\"\",1,0.0"
};
List<Product> list = new List<Product>();
foreach (string line in lines)
{
Product p;
if (TryParseProduct(line, out p)) list.Add(p);
}
foreach (Product p in list)
{
Console.WriteLine(p.Name + " -> " + p.Quantity + " @ " + p.Price);
}
}
}
따옴표로 묶인 필드 규칙
복습
복습: 따옴표가 없는 CSV에는 간단한 Split을 사용하고, TryParse로 숫자를 파싱하며, 필드에 쉼표가 포함될 수 있을 때는 따옴표를 인식하는 스캐너로 전환합니다.
자주 묻는 질문
“간단한 CSV 구문 분석 패턴” 강의는 무료인가요?
네 — “간단한 CSV 구문 분석 패턴” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 3개의 강의가 포함되어 있습니다.
“간단한 CSV 구문 분석 패턴”에서 뭘 배우나요?
CSV 행을 분석합니다. 단순한 파일에는 기본 Split을 사용하고, 숫자에는 안전한 TryParse를 적용한 다음, 따옴표 안의 쉼표를 처리하는 작은 분할기를 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C# Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.
“간단한 CSV 구문 분석 패턴” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- System.IO(경로와 스트림)
- System.Text.Json을 사용한 JSON(선택적 활성화와 변환기)
- 간단한 CSV 구문 분석 패턴