C#/C#200제

[C#] 5일차 (문자, 문자열 정리)

반나무 2021. 1. 20. 11:53

24. 증가연산자, 감소연산자와 대입연산자의 압축

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A024_ConpoundAssignment
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 32;

            Console.WriteLine(x += 2);
            Console.WriteLine(x -= 8);
            Console.WriteLine(x *= 3);
            Console.WriteLine(x /= 2);
            Console.WriteLine(x++ );
            Console.WriteLine(--x);
        }
    }
}

25. String 클래스

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A025_StringMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = " Hello, World! ";
            string t;

            Console.WriteLine("문자열의 길이 : " + s.Length);
            Console.WriteLine("8번째 index : " + s[8]);
            Console.WriteLine("insert : " + s.Insert(8, "C# "));    // 특정 위치에 문자열 삽입
            Console.WriteLine("PadLeft : " + s.PadLeft(20, '.'));   // 앞쪽에 특정문자를 넣어서 문자열의 길이를 맞춤
            Console.WriteLine("PadRight : " + s.PadRight(20, '.')); // 뒷쪽에 특정문자를 넣어서 문자열의 길이를 맞춤
            Console.WriteLine("Remove : " + s.Remove(6));           // n번째 인덱스부터 끝까지 지워줌
            Console.WriteLine("Remove : " + s.Remove(6, 7));        // n번째 인덱스부터 n개의 문자를 지워줌
            Console.WriteLine("Replace : " + s.Replace('l', 'm'));  // 'l'을 'm'으로 바꿔줌
            Console.WriteLine("ToLower : " + s.ToLower());          // 문자열을 대문자로 바꿔줌
            Console.WriteLine("ToUpper : " + s.ToUpper());          // 문자열을 소문자로 바꿔줌
            Console.WriteLine('/' + s.Trim() + '/');                // 앞뒤의 공백문자를 없앰
            Console.WriteLine('/' + s.TrimStart() + '/');           // 앞쪽의 공백문자를 없앰
            Console.WriteLine('/' + s.TrimEnd() + '/');             // 뒤쪽의 공백문자를 없앰

            string[] a = s.Split(',');                              // 문자열을 ,로 구분해 string 배열로만듬
            foreach (var i in a)
                Console.WriteLine('/' + i + '/');

            char[] destinantion = new char[10];
            s.CopyTo(8, destinantion, 0, 6);                        // 문자열의 일부분을 문자배열로 저장 (문자열의 8번째 인덱스 부터, destiantion배열의, 0번쨰로, 6개의 문자를 복사
            Console.WriteLine("destination : " + destinantion);
            Console.WriteLine('/' + s.Substring(8) + '/');          // 문자열의 8번째 index부터 끝까지 return
            Console.WriteLine('/' + s.Substring(8, 5) + '/');       // 문자열의 8번째 index부터 5개의 문자열을 return

            Console.WriteLine(s.Contains("11"));                    // 문자열에 x가 있다면 true를 return
            Console.WriteLine(s.IndexOf('o'));                      // 처음나오는 x의 index번호를 return
            Console.WriteLine(s.LastIndexOf('o'));                  // 맨 마지막으로 나오는 x의 index번호를 return
            Console.WriteLine(s.CompareTo("abc"));                  // 

            Console.WriteLine(String.Concat("Hi~", s));             // 두 개의 문자열을 합쳐줌
            Console.WriteLine(String.Compare("abc", s));            // 
            Console.WriteLine(t = String.Copy(s));                  // 문자열을 복사함

            String[] val = { "apple", "orange", "grape", "pear" };  // 배열의 각 요소를 ','로 연결해 return
            String result = String.Join(", ", val);
            Console.WriteLine("과일 리스트 : " + result);
        }
    }
}

 

26. String.Split() 메소드를 사용 한 문자열 구문 분석

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A026_SplitMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("더하고자 하는 숫자들을 입력하세요 : ");
            string s = Console.ReadLine();
            Console.WriteLine(s);

            int sum = 0;
            string[] v = s.Split();
            foreach(var i in v)
            {
                sum += int.Parse(i);
            }
            Console.WriteLine("결과는 {0}", sum);
        }
    }
}

27. 문자열을 연결하는 4가지 방법

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A027_StringConcat
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "bikang";
            string date = DateTime.Today.ToShortDateString();

            // 1. +를 사용한 문자열 처리
            string strPlus = "Hello " + userName + " .Today is " + date + ".";
            Console.WriteLine(strPlus);

            // 2. Format을 사용한 문자열 처리
            string strFormat = String.Format("Hello {0}. Today is {1}.", userName, date);
            Console.WriteLine(strFormat);

            // 3. 보간을 사용한 문자열 처리
            string strInterpolation = $"Hello {userName}. Today is {date}.";
            Console.WriteLine(strInterpolation);

            // 4. Concat, Join을 사용한 문자열 처리
            string strConcat = String.Concat("Hello ", userName, ". Today is ", date);
            Console.WriteLine(strConcat);

            string[] animal = { "mouser", "cow", "tiger", "rabbit", "dragon" };
            string s = String.Concat(animal);
            Console.WriteLine(s);

            s = String.Join(", ", animal);
            Console.WriteLine(s);


        }
    }
}

28. 문자열의 검색

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A028_StringContains
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "mouse, cow, tiger, rabbit, dragon";
            string s2 = "Cow"; // s2 = "cow" (2가지로 해볼 수 있음)
            bool b = s1.Contains(s2); // s1에 s2가 있는지 판단.(대소문자 구분)
            Console.WriteLine($"{s2} is in the string '{s1}':{b}");

            // 문자열 찾아 index return, 없으면 -1 return
            if (b)
            {
                int index = s1.IndexOf(s2);
                if (index >= 0)
                    Console.WriteLine($"{s2} begins at index {index}");

            }

            // s1에 s2가 있는지 판단. (대소문자 구분없음)
            if(s1.IndexOf(s2, StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                Console.WriteLine($"{s2} is in the string '{s1}'");
            }
        }
    }
}

29. String.Format의 날짜와 시간형식 지정

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A029_StringFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string max = String.Format("0x{0:X} {0:E} {0:N}", Int64.MaxValue);
            Console.WriteLine(max);

            Decimal exchangeRate = 1129.20m;

            string s = String.Format("현재 원달러 환율은 {0}입니다", exchangeRate);
            Console.WriteLine(s);

            // C는 통화방식으로 3자리마다 ,를 넣어줌
            s = String.Format("현재 원달려 환율은 {0:C2}입니다", exchangeRate);
            Console.WriteLine(s);

            s = String.Format("오늘 날짜는 {0:d}, 시간은 {0:t}입니다.", DateTime.Now);
            Console.WriteLine(s);

            // duration은 TimeSpan의 구조체 변수.
            TimeSpan duration = new TimeSpan(1, 12, 23, 62);
            string output = String.Format("소요 시간 : {0:c}", duration);
            Console.WriteLine(output);
        }
    }
}

30. 그룹 분리자를 넣는 방법

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A030_GroupSeparator
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("표시할 숫자를 입력하세요(종료 : -1) : ");
                string s = Console.ReadLine();
                double v = double.Parse(s);

                if(v == -1)
                    break;
                Console.WriteLine(NumberWithGroupSeparator(s));
            }
        }

        // 숫자를 그룹 분리자가 포함된 문자열로 return
        private static string NumberWithGroupSeparator(string s)
        {
            int pos = 0; // 아래자리수를 의미하는 변수
            double v = Double.Parse(s);

            // 소숫점이 있는지 검사해 있다면 
            if (s.Contains("."))
            {
                pos = s.Length - s.IndexOf('.');             // 소숫점 앞자리 까지의 index ex) 12.345 -> index : 4
                string formatStr = "{0:N" + (pos - 1) + "}"; // 소숫점 끝까지 format
                s = string.Format(formatStr, v);
            } else
            {
                s = string.Format("{0:N0}", v);
            }
            return s;
        }
    }
}

31. String과 StringBuilder의 차이점

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace A031_StringBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder("This is a StringBuilder Test.");
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

            // sb초기화
            sb.Clear();
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

            // sb의 맨뒤에 문자열 추가
            sb.Append("This is a new String");
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

            // sb의 5번째 위치에 xyz를 2번 삽입
            sb.Insert(5, "xyz ", 2);
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

            // sb의 5번째 위치에서 4개의 문자 삭제
            sb.Remove(5, 4);
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);

            // sb의 xzy를 찾아 abc로 대체
            sb.Replace("xzy", "abc");
            Console.WriteLine("{0} ({1} characters)", sb.ToString(), sb.Length);


            // string과 stringBuilder의 차이를 위한 타이머 재기
            Stopwatch time = new Stopwatch();
            string test = string.Empty;
            time.Start();
            for(int i=0; i<100000; i++)
            {
                test += i;
            }
            time.Stop();
            Console.WriteLine("String : " + time.ElapsedMilliseconds + "ms");

            StringBuilder test1 = new StringBuilder();
            time.Reset();
            for (int i = 0; i < 100000; i++)
            {
                test1.Append(i);
            }
            time.Stop();
            Console.WriteLine("String : " + time.ElapsedMilliseconds + "ms");

        }
    }
}

반응형