- String.Compare(s1, s2, true|false|null), s1.CompareTo(s1, s2), s1.Equals(s2)

s2>s1 return 1

s1>s2 return -1

s1 == s2 문자의 길이가 같으면, 첫번째 문자의 크기를비교(알파벳상 뒤면 더크다)

true일때는 대소문자 무시(스페이스로두어도됨), 대소문자 구분은 false (a > A)

using System;
					
public class Program
{
	public static void Main()
	{
		string str1 = "Korea";
		string str2 = "Canada";
		string str3 = "Corea";
		string str4 = "korea";
		
		Console.WriteLine("{0} {1}", str1.Length, str2.Length);
		var res1 = String.Compare(str1, str2);  // str2 > str1 return 1
		Console.WriteLine(res1);
		var res2 = String.Compare(str2, str1);  // str2 < str1 return -1
		Console.WriteLine(res2);
		var res3 = String.Compare(str1, str3);  // str1 == str3 and C>K return 1
		Console.WriteLine(res3);
		var res4 = String.Compare(str1, str4, false);  // str1 == str4 and K==K return 0
		Console.WriteLine(res4);
		
		// CompareTo()
		var res5 = str1.CompareTo(str2);
		Console.WriteLine(res5);
		
		// Compare two strings whether same or not: return true | false
		Console.WriteLine(str1.Equals(str2));
	}
}

- ToCharArray(), Split(''), Join(",", arr)

  : ToCharArray(): string을 char array로 변환

  : Split(''): string을 셀렉터로 구분하여 배열로 저장

  : Join('', arr): arr을 셀렉터로 구분하여 스트링으로 저장

using System;
					
public class Program
{
	public static void Main()
	{
		string str1 = "Korea";
		string str2 = “Korea,Japan,China,Canada”;
		
        char[] arr = str1.ToCharArray();
		Console.WriteLine(arr[2]);
		
        string[] arr2 = str1.Split(',');
		Console.WriteLine(arr2[2]);
        
        string str3 = String.Join("-", arr2);
		Console.WriteLine(str3);
	}
}
/* r China Korea-Japan-China-Canada */

- Contains(), IndexOf(), LastIndexOf()

 : Contains(): 문자(열) 포함을 확인 또는 문자열비교  --  return true | false

 : IndexOf(): 문자(열)의 처음나오는 위치를 리턴, 존재하지 않는경우 -1

 : LastIndexOf(): 문자(열)의 마지막 나오는 위치를 리턴 

using System;
					
public class Program
{
	public static void Main()
	{
		string str1 = "Be the reds";
		string str2 = "Be the reds";
		string str3 = "be the reds";
		
		// "the"가 있는지 체크 return true
		Console.WriteLine(str1.Contains("the"));
		
		// "The"가 있는지 체크 return false  --  대소문자 구분
		Console.WriteLine(str1.Contains("The"));
		
		// 두개의 스트링 비교 return true
		Console.WriteLine(str1.Contains(str2));
		
		// 두개의 스트링 비교 return false  -- 대소문자 구분
		Console.WriteLine(str1.Contains(str3));
		
		// 문자 "r"의 위치 출력 return 7, 문자열 검색시 맨첫문자의 위치
		Console.WriteLine(str1.IndexOf("r"));
		
		// 문자 "k"의 위치 출력 return -1  --  존재하지 않음
		Console.WriteLine(str1.IndexOf("k"));
        
        // 문자 "r"의 위치 출력 return 8, 문자열 검색시 해당 문자가 마지막으로 나오는 위치
		// 문자열일 경우 마지막에 나오는 위치중 맨첫문자의 위치
		Console.WriteLine(str1.LastIndexOf("e"));
	}
}
/* True  False  True  False  7  -1  -1  8  */

- Substring(n, num), Insert(n, str), Remove(n, num), Replace(n, str)

 : Substring(): n번째에서 num개 만큼 선택

 : Insert(): n번째에 특정 스트링 입력

 : Remove(): n번째에서 num개 만큼 제거  -- Substring과 Insert의 반대로 볼수도 있다.

 : Replace(): n번째에서 특정 스트링 교환

using System;
					
public class Program
{
	public static void Main()
	{
		string str1 = "Korea, Canada, Japan, China, England";
		
		// 3번째에서 5개 return ea, C
		Console.WriteLine("Substring 1: " + str1.Substring(3,5));
		
		// 7번째에서 모두다 Canada, Japan, China, England
		Console.WriteLine("Substring 2: " + str1.Substring(7));
		
		// 0번째에서 5개  -- ,가 5번째 위치함
		Console.WriteLine("Substring 3: " + str1.Substring(0, str1.IndexOf(',')));
		
		// 6번째에 " Russia," 삽입
		Console.WriteLine("Insert: " + str1.Insert(6, " Russia,"));
		
		// 6번째에서 8개의 캐릭터 제거
		Console.WriteLine("Remove 1: " + str1.Remove(6,8));
		
		// 5번째이후 모두 제거
		Console.WriteLine("Remove 2: " + str1.Remove(5));
		
		// , 를 | 로 변환
		Console.WriteLine("Replace: " + str1.Replace("," , "|"));
	}
}
/*
 Substring 1: ea, C
 Substring 2: Canada, Japan, China, England
 Substring 3: Korea
 Insert: Korea, Russia, Canada, Japan, China, England
 Remove 1: Korea, Japan, China, England
 Remove 2: Korea
 Replace: Korea| Canada| Japan| China| England
*/

- Trim(), TrimStart(), TrimEnd()

 : Trim() 앞뒤공백제거, Trim(‘*’, ‘a’) 앞뒤로 제거할 캐릭터 지정가능

 : TrimStart() 앞쪽 공백제거

 : TrimEnd() 뒷쪽 공백제거

using System;
					
public class Program
{
	public static void Main()
	{
		string str1 = " hello there ";
		string str2 = "w**hello..";
		string str3 = "hhhhello***";
		// Remove whitespaces from both sides
		Console.WriteLine(str1.Trim());
		
		// Remove special characters 앞뒤 다르게
		Console.WriteLine(str2.Trim('w','.'));
		
		// Remove special characters 앞뒤 같게, 같은 캐릭터는 다 없애기
		Console.WriteLine(str3.Trim('h'));
		
		// Remove whitespace from start
		Console.WriteLine(str1.TrimStart());
		
		// Remove whitespace from end
		Console.WriteLine(str1.TrimEnd());
	}
}
/*
 hello there
 **hello
 ello***
 hello there 
  hello there
*/

- ToLower(), ToUpper(), StartsWith(), EndsWith(), GetType(), Sort()

- string.Empty, Length, HasValue

- Convert.ToInt32(str), int.Parse(str)

'ASP.NET C#' 카테고리의 다른 글

Generic(제너릭)  (0) 2021.01.27
yield, paraller, dynamic  (0) 2021.01.21
Delegate, Action, Func  (0) 2021.01.19
Members => Property(프로퍼티)  (0) 2021.01.16
enum(열거형)  (0) 2021.01.15

공통된 코드를 사용하고, 타입만 달라질 경우 사용

1. 일반적인 클래스 사용 (int, string)

// int id, string name
using System;

namespace Example
{
	public class Student
	{
		public int id {get; set;}
		public string name {get; set;}
		public Student(int id, string name)
		{
			this.id = id;
			this.name = name;
		}
		public int getId()
		{
			return this.id;
		}
		public string getName()
		{
			return this.name;
		}		
	}
    		
	public class Program
	{				
		// execute
		public static void Main(string[] args)
		{
			Student st = new Student(10, "John");
			Console.WriteLine(st.getName() + "'s ID is " + st.getId());
		}
	}
}

2. 일반적인 코드 사용(string id, string name) 그런데 타입만 달라진다.

// string id, string name
using System;

namespace Example
{
	public class Student
	{
		public string id {get; set;}
		public string name {get; set;}
		public Student(string id, string name)
		{
			this.id = id;
			this.name = name;
		}
		public string getId()
		{
			return this.id;
		}
		public string getName()
		{
			return this.name;
		}		
	}
    		
	public class Program
	{				
		// execute
		public static void Main(string[] args)
		{
			Student st = new Student("ten", "John");
			Console.WriteLine(st.getName() + "'s ID is " + st.getId());
		}
	}
}	

3. 코드의 낭비를 없애기 위해 제너릭 사용

  : 클래스 선언시 이름 옆에 <T>, 타입이 들어가는 자리에 T 표기

  : 사용시에는 클래스 이름옆에 <타입> 넣어준다

// 제네릭 T : 한개의 변수 사용예정, string id, string name
using System;

namespace Example
{
	public class Student<T>
	{
		public T id {get; set;}
		public T name {get; set;}
		public Student(T id, T name)
		{
			this.id = id;
			this.name = name;
		}
		public T getId()
		{
			return this.id;
		}
		public T getName()
		{
			return this.name;
		}		
	}
    		
	public class Program
	{				
		// execute
		public static void Main(string[] args)
		{
			Student<string> st = new Student<string>("ten", "John");
			Console.WriteLine(st.getName() + "'s ID is " + st.getId());
		}
	}
}	

4. 제네릭 2개의 변수 사용

// 제네릭 T,S 사용
using System;

namespace Example
{
	public class Student<T, S>
	{
		public T id {get; set;}
		public S name {get; set;}
		public Student(T id, S name)
		{
			this.id = id;
			this.name = name;
		}
		public T getId()
		{
			return this.id;
		}
		public S getName()
		{
			return this.name;
		}		
	}
    		
	public class Program
	{				
		// execute
		public static void Main(string[] args)
		{
			Student<int, string> st = new Student<int, string>(10, "John");
			Console.WriteLine(st.getName() + "'s ID is " + st.getId());
		}
	}
}	

'ASP.NET C#' 카테고리의 다른 글

String Manipulation  (0) 2021.01.29
yield, paraller, dynamic  (0) 2021.01.21
Delegate, Action, Func  (0) 2021.01.19
Members => Property(프로퍼티)  (0) 2021.01.16
enum(열거형)  (0) 2021.01.15

yield 키워드

iteration 해주는 키워드

using System;
using System.Collections.Generic;

namespace Example
{   	
	public class Program
	{
		static IEnumerable<int> GetNumber()
		{
			yield return 100;
			yield return 200;
			yield return 300;
		}
				
		// execute
		public static void Main(string[] args)
		{
			foreach(int num in GetNumber())
			{
				Console.WriteLine(num);
			}
		}
	}
}	

 

paraller 키워드

여러개의 cpu 병렬처리 하게끔 도와주는 키워드

Paraller.For(0, 100, (i) => {Console.WriteLine(i + “ “);}

 

dynamic 키워드

컴파일러가 런타임때까지 타입체크를 하지 않는다. dynamic 타입은 object타입을 사용하며, 캐스팅이 필요없다

 

'ASP.NET C#' 카테고리의 다른 글

String Manipulation  (0) 2021.01.29
Generic(제너릭)  (0) 2021.01.27
Delegate, Action, Func  (0) 2021.01.19
Members => Property(프로퍼티)  (0) 2021.01.16
enum(열거형)  (0) 2021.01.15

: 다른 함수를 참조하여 실행하는, 메소드를 참조하는 변수

  [콜백으로 사용: 하나의 메소드에 다양한 delegate를 파라미터로 넣을수있음]

: 이벤트, 스레드동기화, Reflect등에 많이 쓰인다.

: delegate 선언해준다. delegate return_type delegate_name (params)

   // 반환타입과 파라미터 타입은 사용코자 하는 메소드와 동일해야 한다.

: delegate 타입에 변수를 생성하고, 생성된 변수에 해당 메소드를 참조시킨다.

: 사용시에는 생성된 변수에 파라미터를 넣는다.

 

- Delegate 실행

using System;

namespace Example
{
    //Delegate 선언
    delegate void Ex_Dele(int num);
			
	public class Program
	{
        // 대리자 함수
		public static void Ex1_Method(int num)
		{
			Console.WriteLine(num);
		}
        
		// 대리자 함수
		public static void Ex2_Method(int num)
		{
			num += 100;
			Console.WriteLine(num);
		}
		
		// execute
		public static void Main(string[] args)
		{
            // Delegate 변수 선언 및 참조 인스턴스에 대리자함수 입력
			Ex_Dele ed1 = new Ex_Dele(Ex1_Method);
            
            // Delegate 실행
			ed1(100);
			
			Ex_Dele ed2 = new Ex_Dele(Ex2_Method);
			ed2(100);
		}
	}
}	

- Delegate 변수를 파라미터로 사용

  : Delegate와 대리함수를 선언하고, 이 메소드를 값으로 하는 인스턴스를 참조하는 Delegate 변수를 다른 함수의 파라

   미터로 사용

using System;

namespace Example
{
    delegate int Ex_Dele(int num);
			
	public class Program
	{
		public static int Ex_Method(int num)
		{
			return num *= 100;
		}
		
		public static void Ex2_Method(int exd)
		{
			Console.WriteLine(exd);
		}
				
		// execute
		public static void Main(string[] args)
		{
            // Delegate 인스턴스에 메소드를 파라미터로 넣어 ed 변수생성
			Ex_Dele ed = new Ex_Dele(Ex_Method);
            
            // 참조변수를 다른 함수의 파라미터로 사용
			Ex2_Method(ed(1));
			Ex2_Method(ed(10));
		}
	}
}
/*  100  1000  */

- Delegate 콜백함수로 실행

using System;

namespace Example
{
    public delegate int Ex_Dele(int num);
			
	public class Program
	{
		public static int Ex_Method(int num)
		{
			return num *= 100;
		}
		
        // Delegate를 파라미터로 사용
		public static void Ex2_Method(int n, Ex_Dele exd)
		{
            // 파라미터로 받은 값을 delegate 인스턴스의 값으로 입력)
			Console.WriteLine(exd(n));
		}
				
		// execute
		public static void Main(string[] args)
		{
			Ex_Dele ed = new Ex_Dele(Ex_Method);
			
			Ex2_Method(10, ed);
			
		}
	}
}
/* 1000 */

- Delegate 콜백함수로 사용 응용

using System;

namespace Example
{
    // Delegate 선언
    public delegate int CalDelegate(int x, int y);
			
	public class Program
	{
        // Delegate를 파라미터로 받는 함수
		public static void Calculator(int x, int y, string type, CalDelegate cd)
		{
			Console.WriteLine(x + " " + type + " " + y + " is " + cd(x, y));
		}
		
        // 대리함수
		public static int add(int x, int y)
		{
			return x + y;
		}
		
        // 대리함수
		public static int substract(int x, int y)
		{
			return x - y;
		}
		
        // 대리함수
		public static int multiple(int x, int y)
		{
			return x * y;
		}
		
        // 대리함수
		public static int divide(int x, int y)
		{
			return x / y;
		}
				
		// execute
		public static void Main(string[] args)
		{
            // Delegate 변수 선언 및 인스턴스에 대리함수 입력 
			CalDelegate Add = new CalDelegate(add);
			CalDelegate Substract = new CalDelegate(substract);
			CalDelegate Multiple = new CalDelegate(multiple);
			CalDelegate Divide = new CalDelegate(divide);
			
            // Delegate 변수값을 파라미터로 받는 함수실행
			Calculator(10, 20, "add", Add);
			Calculator(30, 10, "substrat", Substract);
			Calculator(10, 20, "multiple", Multiple);
			Calculator(50, 10, "divide", Divide);
		}
	}
}
/*
  10 add 20 is 30
  30 substrat 10 is 20
  10 multiple 20 is 200
  50 divide 10 is 5
*/

Action, Func

  : delegate를 좀더 간편하게 쓰기 위한 메소드

  : Action은 리턴값이 없고, Func는 리턴값을 갖는다(마지막 파라미터가 리턴값)

using System;

namespace Example
{
    //Delegate 선언
    // delegate void Ex_Dele(int num);
			
	public class Program
	{	
        // 대리자 함수
		//public static void Ex1_Method(int num)
		//{
		//	Console.WriteLine(num);
		//}
        
		// 대리자 함수
		//public static void Ex2_Method(int num)
		//{
		//	num += 100;
		//	Console.WriteLine(num);
		//}
		
		// execute
		public static void Main(string[] args)
		{
			// Action - 리턴값이 없음
            Action<int> action = delegate(int num)
			{
				Console.WriteLine(num);
			};
			
            // Func - 리턴값이 int
			Func<int, int> func = delegate (int num)
			{
				num += 100;
				return num;
			};
            
            // Delegate 실행
			action(100);
			Console.WriteLine(func(200));
		}
	}
}
/* 100   300 */

Lambda

  : Action, Func를 더 간단히 표현

using System;

namespace Example
{
    		
	public class Program
	{		
		static Action<int> action;
		static Func<int, int> func;
		
		// execute
		public static void Main(string[] args)
		{
			action = (int num) =>
			{
				Console.WriteLine(num);
			};
			
            // Delegate 변수 선언 및 참조 인스턴스에 대리자함수 입력
			func = (int num) =>
			{
				num += 100;
				return num;
			};
            
            // Delegate 실행
			action(100);
			
			//Ex_Dele ed2 = new Ex_Dele(Ex2_Method);
			Console.WriteLine(func(200));
		}
	}
}
/* 100  300 */

'ASP.NET C#' 카테고리의 다른 글

Generic(제너릭)  (0) 2021.01.27
yield, paraller, dynamic  (0) 2021.01.21
Members => Property(프로퍼티)  (0) 2021.01.16
enum(열거형)  (0) 2021.01.15
상속, abstract, interface, sealed, this, base  (0) 2021.01.12

+ Recent posts