문자열 처리 크게 5가지 방법으로 C# 문자열(String)을 처리할 수 있습니다.
- 바로 변수에 string 문자열을 할당한다.
- string constructor를 이용한다.
- + 오퍼레이터를 이용해서 할당한다.
- Property 또는 string class 메소드를 이용해서 할당할수 있다.
- formatting 메소드를 이용해서 문자열(스트링)을 표현할 수 있다.
<Example Code>
using System; namespace StringApplication { class Program { static void Main(string[] args) { //변수에 바로 문자열을 할당한다. string fname, lname; fname = "Rowan"; lname = "Atkinson"; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //생성자를 이용해서 문자열을 할당한다. char[] letters = { 'H', 'e', 'l', 'l','o' }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //string 에 있는 메소드를 이용해서 할당한다. string[] sarray = { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //포멧팅 함수를 이용해서 문자열을 만든다. DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); Console.ReadKey() ; } } }
<출력>
Full Name: Rowan Atkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
[C# 문자열 자르기(C# Split)]
프로그램을 개발하면서 특정 문자열을 스페이스 ' ' 또는 줄바꿈 '\r\n' 마다 문자열을 잘라서 조작해야 하는 경우가 많을 것입니다.
그럴경우에 C#에서 제고하는 class를 이용해서 간단하게 하는 방법을 알아 보겠습니다.
<스페이스 ' ' 마다 자르는 sample code>
using System; class Program { static void Main() { string s = "there is a cat"; // Split string on spaces. // ... This will separate all the words. string[] words = s.Split(' '); foreach (string word in words) { Console.WriteLine(word); } } }
Output there is a cat
<줄바꿈 \r\n 마다 자르는 sample code>
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string value = "cat\r\ndog\r\nanimal\r\nperson";
// Split the string online breaks.
// ... The return value from Split is a string array.
string[] lines = Regex.Split(value, "\r\n");
foreach (string line in lines)
{
Console.WriteLine(line);
}
}
}
Output
cat
dog
animal
person
'C#(CSharp) > 기초강좌(Basic)' 카테고리의 다른 글
[16] C# 클래스 생성자, 파괴자, 스택틱 (C# class, constructor, destructor, static) (0) | 2015.02.23 |
---|---|
[15] C# Enum (0) | 2015.02.23 |
[13] C# 배열 (C# Array and foreach) (0) | 2015.02.23 |
[12] C# Nullables (널 가능) (0) | 2015.02.23 |
[11] C# 메소드 Method (Call by Value, Call by Reference, Output Parameter) (0) | 2015.02.23 |