loading

프로그래밍/C#

C# Left, Right 함수 구현

침착곰 2021. 4. 16. 15:45
반응형

안녕하세요

C#에서 Left, Right함수를 구현해보겠습니다

MS-SQL에서 문자열을 자를 때 Left, Right함수를 사용해서 편하게 쿼리문을 구현했는데 C#에서는 그게 안되더군요 ㅠ

간단하게 메소드를 구현해서 Left, Right를 사용합니다.

솔직히 Left는 SubString으로 구현하면 되는... ㄷㄷ

 

1. 최종 소스

LeftRight.zip
0.18MB

 

2. Left 함수

 Substring을 사용해서 Left함수를 구현합니다

  String보다 Length가 큰 경우 String의 길이를 그대로 사용합니다

1
2
3
4
5
6
7
8
// Left 메소드
public string Left(string str, int Length)
{
    if (str.Length < Length)
        Length = str.Length;
 
    return str.Substring(0, Length);
}
cs

 

3. Right 함수

 마찬가지로 Substring을 사용하지만 시작점을 구할 때 전체문자열 길이에서 넘어온 파라미터 Length를 빼서 시작점을 구합니다

Left함수와 마찬가지로 String보다 Length가 큰 경우 String의 길이를 그대로 사용합니다

1
2
3
4
5
6
7
8
// Right 메소드
public string Right(string str, int Length)
{
    if (str.Length < Length)
        Length = str.Length;
 
    return str.Substring(str.Length - Length, Length);
}
cs

 

4. 전체 소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace LeftRight
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        // Left적용 버튼 클릭 이벤트
        private void btnLeft_Click(object sender, EventArgs e)
        {
            txtAfter.Text = Left(txtBefore.Text, Int32.Parse(txtLength.Text));
        }
 
        // Right적용 버튼 클릭 이벤트
        private void btnRight_Click(object sender, EventArgs e)
        {
            txtAfter.Text = Right(txtBefore.Text, Int32.Parse(txtLength.Text));
        }
 
        // Left 메소드
        public string Left(string str, int Length)
        {
            if (str.Length < Length)
                Length = str.Length;
 
            return str.Substring(0, Length);
        }
 
        // Right 메소드
        public string Right(string str, int Length)
        {
            if (str.Length < Length)
                Length = str.Length;
 
            return str.Substring(str.Length - Length, Length);
        }
    }
}
 
cs

 

5. 결과 화면

 Left적용을 클릭하면 왼쪽의 3개가 출력되는 것을 볼 수 있습니다

 

 Right적용을 클릭하면 오른쪽의 3개가 출력되는 것을 볼 수 있습니다

 

여기까지 Left, Right 함수를 구현한 방법에 대해서 알아봤습니다

C# 개발에 참고가 되셨으면 좋겠습니다

반응형
그리드형