달력

2

« 2025/2 »

  • 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
2016. 6. 22. 02:55

String 클래스 프로그래밍/C#2016. 6. 22. 02:55

String 클래스


https://msdn.microsoft.com/ko-kr/library/system.string(v=vs.110).aspx


1. 텍스트를 UTF-16 코드 단위의 시퀀스로 나타냅니다.

2. 이 유형에 대한 .NET Framework 소스 코드를 찾아보려면(browser) Reference Source를 참조하세요.





String 생성자 (Char, Int32)


1. 지정된 횟수만큼(a specified number of times) 반복되는 지정되는 유니코드 문자가 나타내는 값으로 String 클래스의 새 인스턴스를 초기화합니다.

<구문>

public String(
	char c,
	int count
)

<매개 변수>

c : 유니코드 문자입니다.

count : c가 발생하는 횟수



String 생성자 (Char[])


1. 유니코드 문자의 배열이 나타내는 값으로 String 클래스의 새로운 인스턴스를 초기화합니다.

<구문>

public String(
	char[] value
)

<매개 변수>
value : 유니코드 문자 배열



String 생성자 (Char[], Int32, Int32)


1. 유니코드 문자 배열이 나타내는 값, 해당 배열 내의 시작 문자 위치, 길이로 String 클래스의 새로운 인스턴스를 생성합니다.

<구문>

public String(
	char[] value,
	int startIndex,
	int length
)

<매개 변수>

value : 유니코드 문자 배열입니다.

startIndex : value 내의 시작 위치입니다.

length : value 내에서 사용할 문자의 수입니다.





String.Compare (String, String)


1. 지정된 두 String 개체를 비교하고 정렬 순서에서(in the sort order) 두 개체의 상대 위치(their relative position)를 나타내는 정수를 반환합니다.


<구문>

public static int Compare(
	string strA,
	string strB
)


<매개 변수>

strA : 비교할 첫째 문자열입니다.

strB : 비교할 둘째 문자열입니다.


<반환 값>

Type: System.Int32

두 비교 대상 간(the two comparands)의 어휘 관계(lexical relationship)를 나타내는 32비트 부호 있는 정수입니다.

 값

 조건 

 0보다 작음

 정렬 순서에서 strA가 strB 앞에 오는(precede) 경우 

 0

 정렬 순서에서 strA와 strB가 동일한 위치

 0보다 큼

 정렬 순서에서 strA가 strB 뒤에 오는(follow) 경우 


<설명>

1. 비교(the comparison)는 대/소문자 규칙(casing rules)과 개별 문자(individual characters)의 사전 순(the alphabetic order) 같은 문화 특정 정보(culture-specific information)를 얻기 위해서 현재 문화권(the current culture)을 사용합니다.

2. 예를 들면, 특정 문자 조합(certain combinations of characters)이 단일 문자(a single character)로 처리되어야 하는지 또는 대소문자가 특정한 방식으로 비교되어야 하는지 또는 문자의 정렬 순서(the sorting order)가 앞에 또는 뒤에 오는 문자에 따라 달라지는지를 지정할 수 있습니다.

3. 단어 정렬 규칙(word sort rules)을 사용하여 비교를 수행합니다.

4. 단어, 문자열, 서수 정렬에 대한 자세한 정보는 System.Globalization.CompareOptions를 참조하십시오.


 경고

 문자열을 비교할 때, 문자열 비교 형식을 명시적으로 지정하는 Compare(String, String, StringComparison)을 호출해야 합니다.


5. 하나 또는 두 비교 대상(comparands)이 null이 될 수 있습니다.

6. 정의에 따라서 빈 문자열을 포함하는 모든 문자열이 null 참조보다 큰지, 두 null 참조가 서로 같은지를 비교합니다.

7. 비교는 같지 않음(inequality)이 발견되거나 두 문자열 비교가 완료되면 종료됩니다.

8. 그러나 두 문자열 중에서 한 문자열의 끝에서 같고 다른 문자열의 문자가 남아 있다면 남아 있는 문자를 가진 문자열이 더 큰 것으로 고려됩니다.

9. 반환 값은 마지막으로 수행한 비교 결과입니다.

10. 비교가 문화권 특정 규칙에 영향을 받는 다면 예기치 못한 결과가 발생할 수 있습니다.

11. 터키어에서(in Turkish) 다음 예제는 잘못된 결과가 발생합니다.

12. 왜냐하면 터키어의 파일 시스템에서는 file에서 문자 i가 언어적 대/소문자 규칙을 사용하지 않기 때문입니다.


static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, true) == 0);
}


13. 서수 비교를 사용하여 "file"에 경로 이름을 비교합니다.

14. 이에 대한 올바른 코드는 다음과 같습니다.


static bool IsFileURI(String path)
{
    return (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0);
}


<호출자 참고 사항>

15. 문자 집합(Character sets)에는 무시할 수 있는(ignorable) 문자가 포함됩니다.

16. Compare(String, String) 메서드는 문화권 구분 비교(a culture-sensitive comparison)를 수행하는 경우 이러한 문자를 고려하지 않습니다.

17. 예를 들어 .NET Framework 4 이후의 버전에서 다음 코드가 실행된다면 "animal"과 "ani-mal"(소프트 하이픈 또는 U+00AD 사용)의 문화권 구분 비교는 두 문자열이 동일하다고 보여줍니다.


using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      string s2 = "animal";

      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0


18. 문자열 비교에서 무시할 수 있는 문자를 인식하려면(recognize) Compare(String, String, StringComparison) 메서드를 호출하고 comparisonType 매개 변수에 대한 CompareOptions.Ordinal 또는CompareOptions.OrdinalIgnoreCase의 값을 지정하세요.

<예제>

19. 다음 예제에서는 ReverseStringComparer 클래스는 Compare 메서드로 두 문자열을 계산하는 방법을 보여줍니다.


using System;
using System.Text;
using System.Collections;

public class SamplesArrayList  {

	public static void Main()  {
		// Creates and initializes a new ArrayList.
		ArrayList myAL = new ArrayList();
		myAL.Add("Eric");
		myAL.Add("Mark");
		myAL.Add("Lance");
		myAL.Add("Rob");
		myAL.Add("Kris");
		myAL.Add("Brad");
		myAL.Add("Kit");
		myAL.Add("Bradley");
		myAL.Add("Keith");
		myAL.Add("Susan");

		// Displays the properties and values of	the	ArrayList.
		Console.WriteLine( "Count: {0}", myAL.Count );

		PrintValues ("Unsorted", myAL );
		myAL.Sort();
		PrintValues("Sorted", myAL );
		myAL.Sort(new ReverseStringComparer() );
		PrintValues ("Reverse" , myAL );


		string [] names = (string[]) myAL.ToArray (typeof(string));


	}
	public static void PrintValues(string title, IEnumerable	myList )  {
		Console.Write ("{0,10}: ", title);
		StringBuilder sb = new StringBuilder();
		foreach (string s in myList) {
			sb.AppendFormat( "{0}, ", s);
		}
		sb.Remove (sb.Length-2,2);
		Console.WriteLine(sb);
	}
}
public class ReverseStringComparer : IComparer {
   public int Compare (object x, object y) {
	   string s1 = x as string;
	   string s2 = y as string;	  
	   //negate the return value to get the reverse order
	   return - String.Compare (s1,s2);

   }
}





String.Compare (String, String, Boolean)


1. 대/소문자를 구분하거나 구분하지 않고 두 지정된 문자열 객체를 비교해서 정렬 순서에 따른 상대적 위치를 나타내는 정수 값을 반환합니다.

<구문>

public static int Compare(
	string strA,
	string strB,
	bool ignoreCase
)

<매개 변수>

strA : 비교할 첫째 문자열입니다.

strB : 비교할 둘째 문자열입니다.

ignoreCase : 비교 시 대/소문자를 무시하려면 true, 그렇지 않으면 false입니다.


using System;

public class Example
{
   public static void Main()
   {
      string s1 = "Ani\u00ADmal";
      string s2 = "animal";

      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, s2, String.Compare(s1, s2, true));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0


<예제>

2. 다음 예제에서는 Compare(String, String, Boolean 메서드가 ToUpper 또는 ToLower 사용과 동일하다는 것을 보여줍니다.


using System;

class Example
{
   static void Main()
   {
      // Create upper-case characters from their Unicode code units.
      String stringUpper = "\x0041\x0042\x0043";

      // Create lower-case characters from their Unicode code units.
      String stringLower = "\x0061\x0062\x0063";

      // Display the strings.
      Console.WriteLine("Comparing '{0}' and '{1}':", 
                        stringUpper, stringLower);

      // Compare the uppercased strings; the result is true.
      Console.WriteLine("The Strings are equal when capitalized? {0}",
                        String.Compare(stringUpper.ToUpper(), stringLower.ToUpper()) == 0 
                                       ? "true" : "false");

      // The previous method call is equivalent to this Compare method, which ignores case.
      Console.WriteLine("The Strings are equal when case is ignored? {0}",
                        String.Compare(stringUpper, stringLower, true) == 0
                                       ? "true" : "false" );
   }
} 
// The example displays the following output:
//       Comparing 'ABC' and 'abc':
//       The Strings are equal when capitalized? true
//       The Strings are equal when case is ignored? true





String.Compare (String, Int32, String, Int32, Int32)


1. 두 지정된 String 객체의 부분 문자열(substrings)을 비교해서 정렬 순서의 상대 위치(relative position)를 나타내는 정수를 반환합니다.

<구문>

public static int Compare(
	string strA,
	int indexA,
	string strB,
	int indexB,
	int length
)


<매개 변수>

strA : 비교할 첫번째 문자열

indexA : strA 내의 부분 문자열의 위치

strB : 비교할 두번째 문자열

indexB : strB 내의 부분  문자열의 위치

length : 부분 문자열에서 비교할 문자 길이

<반환 값>

두 비교 대상의 어휘적 관계(the lexical relationship)를 나타내는 32-bit 부호 있는 정수

0보다 작음 (Less than zero) : 정렬 순서에서 strA가 strB보다 앞에 있다(precede).

0 (Zero) : 부분 문자열에서 정렬 순서가 같거나 길이가 0이다.

0보다 큼 (Greater than zero) : strA가 strB 뒤에 있다(follow).

<설명>

2. 비교할 부분 문자열은 strA의 indexA 위치에서 그리고 strB의 indexB 위치에서 시작한다.

3. indexA와 indexB 둘다 zero-based 이다. 즉 strA와 strB의 첫 문자는 0의 위치이다.

4. 첫번째 부분 문자열의 길이는 strA의 길이 - indexA + 1 과 동일하다.

5. 두번째 부분 문자열의 길이는 strB의 길이 - indexB + 1 과 동일하다.

6. 비교할 문자 개수는 두 부분 문자열의 길이와 length 보다 적다.

7. indexA, indexB 그리고 length 매개 변수는 양수이어야 한다(nonnegative).

<예제> 

// Sample for String.Compare(String, Int32, String, Int32, Int32)
using System;

class Sample {
    public static void Main() {
//                 0123456
    String str1 = "machine";
    String str2 = "device";
    String str;
    int result;

    Console.WriteLine();
    Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
    result = String.Compare(str1, 2, str2, 0, 2);
    str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal to"));
    Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
    Console.Write("{0} ", str);
    Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);
    }
}
/*
This example produces the following results:

str1 = 'machine', str2 = 'device'
Substring 'ch' in 'machine' is less than substring 'de' in 'device'.
*/






Strig.Compare (String, Int32, String, Int32, Int32, Boolean)


1. 대/소문자를 구분(honor case)하거나 구분하지 않고 정렬 순서에 따른 상대 위치를 나타내는 정수 반환

<구문>

public static int Compare(
	string strA,
	int indexA,
	string strB,
	int indexB,
	int length,
	bool ignoreCase
)

<매개 변수>

strA : 비교할 첫번째 문자열

indexA : strA 내의 부분 문자열의 위치

strB : 비교할 두번째 문자열

indexB : strB 내의 부분  문자열의 위치

length : 부분 문자열에서 비교할 문자 길이

ignoreCase : 대/소문자 무시는 true, 그렇지 않으면 false

<반환 값>

두 비교 대상의 어휘적 관계(the lexical relationship)를 나타내는 32-bit 부호 있는 정수

0보다 작음 (Less than zero) : 정렬 순서에서 strA가 strB보다 앞에 있다(precede).

0 (Zero) : 부분 문자열에서 정렬 순서가 같거나 길이가 0이다.

0보다 큼 (Greater than zero) : strA가 strB 뒤에 있다(follow).

<예제>

2. 다음 예제에서는 두 부분 문자열의 대/소문자의 차이에 대한 두가지 비교를 수행합니다.

3. 첫번째 비교는 대/소문자를 무시하고 두번째 비교에서는 대/소문자를 비교합니다.





String.Compare (String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)


1. 지정된 비교 옵션과 문화권특정 정보를 사용해서 지정된 두 String 객체의 부분 문자열을 비교하고 정렬 순서에서 두 부분 문자열의 관계를 나타내는 정수를 반환합니다.

<구문>

public static int Compare(
	string strA,
	int indexA,
	string strB,
	int indexB,
	int length,
	CultureInfo culture,
	CompareOptions options
)

<매개 변수>

strA : 비교할 첫번째 문자열

indexA : strA 내의 부분 문자열의 위치

strB : 비교할 두번째 문자열

indexB : strB 내의 부분  문자열의 위치

length : 부분 문자열에서 비교할 문자 길이

culture : 문화권특정 비교 정보를를 제공하는 객체

options : 대/소문자 또는 기호 무시 여부와 같은 비교를 수행할 때 사용할 옵션입니다.

<반환값>

두 비교 대상의 어휘적 관계(the lexical relationship)를 나타내는 32-bit 부호 있는 정수

0보다 작음 (Less than zero) : 정렬 순서에서 strA가 strB보다 앞에 있다(precede).

0 (Zero) : 부분 문자열에서 정렬 순서가 같거나 길이가 0이다.

0보다 큼 (Greater than zero) : strA가 strB 뒤에 있다(follow).

<설명>

2. 비교할 부분 문자열의 시작 위치는 strA의 indexA 위치, strB의 indexB 위치입니다.

3. 첫번째 부분 문자열의 길이는 strA - indexA입니다.

4. 두번째 부분 문자열의 길이는 strB - indexB입니다.

5. 비교는 culture 매개 변수를 사용해서 문화권특정 정보(예: 데/소문자 규칙(casing rules과 개별 문자의 알파벳 순서)를 얻습니다.

6. 예를 들면, 특정 문화권(a particular culture)은 특정 문자 조합이 단일 문자로 다루어 져야하는지, 대문자와 소문자 문자가 특정 방식으로 비교되어야 하는지, 문자의 정렬 순서가 앞에 또는 뒤에 오는 문자에 따라 달라지는지를 지정할 수 있습니다.

 주의

 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions 메서드는 주로 정렬(sorting) 또는 알파벳 작업(alphabetizing operations)을 위해서 디자인 되었습니다.  메서드 호출의 주요 목적(the primary purpose)이 두 부분 문자열이 동일한지를 확인하기 위한 것이라면 사용해서는 안됩니다(즉, 메서드 호출의 목적이 0을 리턴하는지 검사).두 문자열이 동일한지 확인하려면 Equals 메서드를 호출하세요.


7. strA와 strB 중에서 한개만 null이거나 두 개 모두 null일 수 있습니다.

8. 정의에 따르면(By definition), String.Empty을 포함한 모든 문자열은 null 참조보다 크다고 비교합니다.

9. 두 null 참조는 서로 동일하다고 비교합니다.

10. 비교는 options 매개 변수로 추가로 지정될 수 있습니다.

11. options 매개 변수는 System.Globalization.CompareOptions 열거형(enumeration)의 한 개 이상의 멤버로 구성됩니다.

12. 이 메서드의 목적은 문화권 구분 문자열 비교 수행이기 때문에 CompareOptions.Ordinal과 CompareOptions.OrdinalIgnoreCase 값은 아무런 효과가 없습니다.

13. 불일치(inequality)가 발견되거나 두 부분 문자열이 비교가 완료 되면 비교는 종료됩니다.

14. 그러나 두 문자열 중에서 한 문자열의 끝까지 비교가 되고 다른 문자열은 남아있는 문자열이 있다면 남아있는 문자열을 가진 문자열이 더 크다고 간주됩니다.

15. 반환 값은 마지막으로 수행된 비교의 결과입니다.

<호출자 참고 사항>

16. 문자 집합은 무시할 수 있는 문자가 포함됩니다

17. Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 메서드는 언어(linguistic 또는 문화권 구분 비교)를 수행할 때 이러한 문자는 고려하지 않습니다.

18. 비교에 무시할 수 있는 문자를 인식하려면(recognize) options 매개 변수에 CompareOptions.Ordinal 또는 CompareOptions.OrdinalIgnoreCase의 값을 제공하세요.

19. 다음 예제는 두 사람의 성(last name)을 비교하기 위해서 Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions) 메서드를 사용합니다.

20. 사전순으로 나열합니다(It then lists them in alphabetical order).


using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string name1 = "Jack Smith";
      string name2 = "John Doe";

      // Get position of space character.
      int index1 = name1.IndexOf(" ");
      index1 = index1 < 0 ? 0 : index1--;

      int index2 = name2.IndexOf(" ");
      index1 = index1 < 0 ? 0 : index1--;

      int length = Math.Max(name1.Length, name2.Length);

      Console.WriteLine("Sorted alphabetically by last name:");
      if (String.Compare(name1, index1, name2, index2, length, 
                         new CultureInfo("en-US"), CompareOptions.IgnoreCase) < 0)
         Console.WriteLine("{0}\n{1}", name1, name2); 
      else
         Console.WriteLine("{0}\n{1}", name2, name1); 
   }
}
// The example displays the following output:
//       Sorted alphabetically by last name:
//       John Doe
//       Jack Smith





CompareTo (Object)


1. 이 인스턴스를 지정된 Object와 비교하고 정렬 순서에서 이 인스턴스의 위치가 지정된 Object보다 앞인지, 뒤인지, 동일한지를 나타냅니다.

<구문>

public int CompareTo(
	object value
)

<매개 변수>

value : String이 되는 개체입니다.

<반환 값>

정렬 순서에서 이 인스턴스의 위치가 value 매개 변수보다 앞인지, 뒤인지, 동일한지를 나타내는 32비트 부호 있는 정수입니다.

0보다 작음 : 이 인스턴스는 value 앞에 오는 경우

0 : 이 인스턴스의 위치가 정렬 순서에서 value와 같은 경우

0보다 큼 : 이 인스턴스는 value 다음에 오는 경우 또는 value가 null인 경우

<구현>

IComparable.CompareTo(Object)

<예외>

ArgumentException : Value가 String이 아닌 경우

<설명>

1. value는 String 객체이어야 합니다.

2. CompareTo 메서드는 주로(primarily) 정렬 또는 사전순 작업(alphabetizing operations)에서 사용할 수 있도록 설계되었습니다.

3. 메서드 호출의 주요 목적이 두 문자열이 동일한지를 확인하기 위해서라면 사용해서는 안됩니다.

4. 두 문자열이 동일한지를 확인하려면 Equals 메서드를 사용하세요

5. 이 메서드는 현재 문화권을 사용해서 단어(대/소문자 구분 및 문화권 구분) 비교를 수행합니다.

6. 단어, 문자열, 서수 정렬에 대한 자세한 내용은 System.Globalization.CompareOptions 메서드를 참조하십요.

7. 이 메서드의 동작에 대한 자세한 내용은 String.Comapre(string, string) 메서드의 주의 섹션(Remarks section)을 참조하십시오.

<호출자 참고사항>

1. 문자 집합(Character sets)에는 무시할 수 있는 문자(ignorable characters)가 포함됩니다.

2. CompareTo 메서드는 문화권 구분 비교를 수행하는 경우 이러한 문자를 고려하지 않습니다.

3. 예를 들면, 다음 코드가 .NET Framework 4 이후 버전에서 실행되는 경우, "animal"과 "ani-mal"의 비교는(soft-hyphen, 즉 U+00AD 사용) 두 문자열이 동일하다고 나타냅니다.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      object o1 = "animal";

      Console.WriteLine("Comparison of '{0}' and '{1}': {2}", 
                        s1, o1, s1.CompareTo(o1));
   }
}
// The example displays the following output:
//       Comparison of 'ani-mal' and 'animal': 0

4. 문자열 비교에서 무시할 수 있는 문자를 인식하려면 CompareOrdinal(String, String) 메서드를 호출하세요.

<예제>

1. 다음 예제에서는 Object와 함께 CompareTo 메서드를 사용합니다.

2. 문자열 인스턴스를 TestClass 객체에 비교를 시도하기 때문에 ArgumentException을 던집니다.


using System;

public class TestClass
{}

public class Example 
{
   public static void Main()
   {
      var test = new TestClass();
      Object[] objectsToCompare = { test, test.ToString(), 123,
                                    123.ToString(), "some text",
                                    "Some Text" };
      string s = "some text";
      foreach (var objectToCompare in objectsToCompare) {
         try {
            int i = s.CompareTo(objectToCompare);
            Console.WriteLine("Comparing '{0}' with '{1}': {2}",
                              s, objectToCompare, i);
         }
         catch (ArgumentException) {
            Console.WriteLine("Bad argument: {0} (type {1})",
                              objectToCompare,
                              objectToCompare.GetType().Name);
         }
      }
   }
}
// The example displays the following output:
//    Bad argument: TestClass (type TestClass)
//    Comparing 'some text' with 'TestClass': -1
//    Bad argument: 123 (type Int32)
//    Comparing 'some text' with '123': 1
//    Comparing 'some text' with 'some text': 0
//    Comparing 'some text' with 'Some Text': -1






String.CompareTo (String)


<구문>

public int CompareTo(
	string strB
)

<매개 변수>

strB : 이 인스턴스와 비교할 문자열

<예제>

다음 예제에서는 CompareTo(Object) 메서드를 사용해서 현재 문자열 인스턴스와 다른 문자열을 비교합니다.

using System;

public class Example
{
   public static void Main()
   {
      string strFirst = "Goodbye";
      string strSecond = "Hello";
      string strThird = "a small string";
      string strFourth = "goodbye";

      // Compare a string to itself.
      Console.WriteLine(CompareStrings(strFirst, strFirst));

      Console.WriteLine(CompareStrings(strFirst, strSecond));
      Console.WriteLine(CompareStrings(strFirst, strThird));

      // Compare a string to another string that varies only by case.
      Console.WriteLine(CompareStrings(strFirst, strFourth));
      Console.WriteLine(CompareStrings(strFourth, strFirst));
   }

   private static string CompareStrings( string str1, string str2 )
   {
      // Compare the values, using the CompareTo method on the first string.
      int cmpVal = str1.CompareTo(str2);

	   if (cmpVal == 0) // The strings are the same.
         return "The strings occur in the same position in the sort order.";
      else if (cmpVal > 0)
         return "The first string precedes the second in the sort order.";
      else
         return "The first string follows the second in the sort order.";
    }
}
// The example displays the following output:
//       The strings occur in the same position in the sort order.
//       The first string follows the second in the sort order.
//       The first string precedes the second in the sort order.
//       The first string precedes the second in the sort order.
//       The first string follows the second in the sort order.






String.Concat (String, String)



1. String.의 지정된 두 인스턴스를 연결합니다(concatenate).

<구문>

public static string Concat(
	string str0,
	string str1
)

<매개 변수>

str0 : 연결할 첫 번째 문자열

str1 : 연결할 두 번째 문자열

<반환 값>

연결된 str0과 str1

<설명>

이 메서드는 str0과 str1을 열결하지만 구분 기호(delimiters)는 추가하지 않습니다.

null 인수 대신에 Empty 문자열이 사용됩니다.

<예제>

다음 예제에서는 사용자의 이름 및 성을 연결합니다.


using System;

public class ConcatTest {
    public static void Main() {

        // we want to simply quickly add this person's name together
        string fName = "Simon";
        string mName = "Jake";
        string lName = "Harrows";

        // because we want a name to appear with a space in between each name, 
        // put a space on the front of the middle, and last name, allowing for
        // the fact that a space may already be there
        mName = " " + mName.Trim();
        lName = " " + lName.Trim();

        // this line simply concatenates the two strings
        Console.WriteLine("Welcome to this page, '{0}'!", string.Concat( string.Concat(fName, mName), lName ) );
    }
}
// The example displays the following output:
//        Welcome to this page, 'Simon Jake Harrows'!





String.Concat (String, String, String)



1. String.의 지정된 세 인스턴스를 연결합니다(concatenate).

<구문>

public static string Concat(
	string str0,
	string str1,
	string str2
)


<매개 변수>

str0 : 연결할 첫 번째 문자열

str1 : 연결할 두 번째 문자열

str2 : 연결할 세 번째 문자열

<반환 값>

연결된 str0, str1, str2를 반환합니다.

<설명>

메서드는 str0, str1, str2를 연결하지만 구분 기호는 추가(demiliters) 하지 않습니다.

null 인수(argument) 대신에 Empty 문자열이 사용됩니다.

<예제>

다음 예제에서는 Concat 메서드를 사용해서 콘솔에 출력됩니다.


using System;
 using System.Globalization; 

public class MainClass { 
    public static void Main(string[] args)  {
        DateTime dt = DateTime.Now;
        String[] format = {
            "d", "D",
            "f", "F",
            "g", "G",
            "m",
            "r",
            "s",
            "t", "T",
            "u", "U",
            "y",
            "dddd, MMMM dd yyyy",
            "ddd, MMM d \"'\"yy",
            "dddd, MMMM dd",
            "M/yy",
            "dd-MM-yy",
        };
        String date;
        for (int i = 0; i < format.Length; i++) {
            date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);
            Console.WriteLine(String.Concat(format[i], " :" , date));
        }

   /** Output.
    *
    * d :08/17/2000
    * D :Thursday, August 17, 2000
    * f :Thursday, August 17, 2000 16:32
    * F :Thursday, August 17, 2000 16:32:32
    * g :08/17/2000 16:32
    * G :08/17/2000 16:32:32
    * m :August 17
    * r :Thu, 17 Aug 2000 23:32:32 GMT
    * s :2000-08-17T16:32:32
    * t :16:32
    * T :16:32:32
    * u :2000-08-17 23:32:32Z
    * U :Thursday, August 17, 2000 23:32:32
    * y :August, 2000
    * dddd, MMMM dd yyyy :Thursday, August 17 2000
    * ddd, MMM d "'"yy :Thu, Aug 17 '00
    * dddd, MMMM dd :Thursday, August 17
    * M/yy :8/00
    * dd-MM-yy :17-08-00
    */
    }
}





String.Concat (String, String, String)



1. String.의 지정된 네 인스턴스를 연결합니다(concatenate).

<구문>

public static string Concat(
	string str0,
	string str1,
	string str2,
	string str3
)

<매개 변수>

str0 : 연결할 첫 번째 문자열

str1 : 연결할 두 번째 문자열

str2 : 연결할 세 번째 문자열

str3 : 연결할 세 번째 문자열

<반환 값>

연결된 str0, str1, str2, str3를 반환합니다.

<설명>

이 메서드는 str0, str1, str2, str3을 연결하지만 구분 기호(delimiters)를 추가하지 않습니다.

빈 문자열이 배열에 있는 null 객체를 대신해서 사용됩니다.

<예제>

다음 예제에서는 4문자로 된 단어의 배열을 정의하고 스크램블 하기 위해서 개별 문자(individual letters)를 문자열 배열에 저장합니다. 그런 다음 Concat(String, String, String, String) 메서드를 호출해서 스크램블된 단어를 재조립합니다(reassemble).


using System;
using System.Collections;

public class Example
{
   public static void Main()
   {
      const int WORD_SIZE = 4;

      // Define some 4-letter words to be scrambled.
      string[] words = { "home", "food", "game", "rest" };
      // Define two arrays equal to the number of letters in each word.
      double[] keys = new double[WORD_SIZE];
      string[] letters = new string[WORD_SIZE];
      // Initialize the random number generator.
      Random rnd = new Random();

      // Scramble each word.
      foreach (string word in words)
      {
         for (int ctr = 0; ctr < word.Length; ctr++)
         {
            // Populate the array of keys with random numbers.
            keys[ctr] = rnd.NextDouble();
            // Assign a letter to the array of letters.
            letters[ctr] = word[ctr].ToString();
         }   
         // Sort the array. 
         Array.Sort(keys, letters, 0, WORD_SIZE, Comparer.Default);      
         // Display the scrambled word.
         string scrambledWord = String.Concat(letters[0], letters[1], 
                                              letters[2], letters[3]);
         Console.WriteLine("{0} --> {1}", word, scrambledWord);
      } 
   }
}
// The example displays output like the following:
//       home --> mheo
//       food --> oodf
//       game --> aemg
//       rest --> trse





String.Concat (String[])


1. 지정된 String 배열의 요소를 연결합니다.

<구문>

public static string Concat(
	params string[] values
)

<매개 변수>

values : 문자열 인스턴스의 배열

<반환 값>

values의 연결된 요소

<예외>

ArgumentNullException : values가 null인 경우

OutOfMemoryException : 메모리가 부족합니다.

<설명>

1. 메서드는 values의 각 객체를 연결하지만 구분 기호를 추가하지 않습니다.

2. 빈 문자열이 배열의 null 객체에 대신해서 사용됩니다.

<예제>

다음 예제에서는 String 배열의 Concat 메서드 사용을 보여줍니다.

using System;

public class Example
{
    public static void Main()
    {
        // Make an array of strings. Note that we have included spaces.
        string [] s = { "hello ", "and ", "welcome ", "to ",
                        "this ", "demo! " };

        // Put all the strings together.
        Console.WriteLine(string.Concat(s));

        // Sort the strings, and put them together.
        Array.Sort(s);
        Console.WriteLine(string.Concat(s));
    }
}
// The example displays the following output:
//       hello and welcome to this demo!
//       and demo! hello this to welcome





String.Contains (String)


1. 이 문자열 내에 지정된 부분 문자열이 포함되어 있는지를 나타내는 값을 반환합니다.

<구문>

public bool Contains(
	string value
)

<매개 변수>

value : 검색할 문자열(The string to seek)

<반환 값>

1. 이 문자열 내에서 value 매개 변수가 존재한다면 또는 value가 빈 문자열("")이라면 true 반환

2. 그렇지 않으면 false 반환

<예외>

ArgumentNullException : value가 null인 경우

<설명>

1. 이 메서드는 서수 비교를 수행합니다.(대/소문자 구분 및 문화권 비구분)

2. 검색은 문자열의 첫 번째 문자 위치에서 시작해서 마지막 문자 위치까지 계속됩니다.

<예제>

다음 예제에서는 문자열 "fox"가 익숙한 따옴표(a familiar quotation) 안의 부분 문자열인지 확인합니다.

using System;

class Example
{
    public static void Main() 
    {
       string s1 = "The quick brown fox jumps over the lazy dog";
       string s2 = "fox";
       bool b = s1.Contains(s2);
       Console.WriteLine("'{0}' is in the string '{1}': {2}",
                          s2, s1, b);
       if (b) {
          int index = s1.IndexOf(s2);
          if (index >= 0)
             Console.WriteLine("'{0} begins at character position {1}",
                               s2, index + 1);
       }
    }
}
// This example display the following output:
//    'fox' is in the string 'The quick brown fox jumps over the lazy dog': True
//    'fox begins at character position 17





String.Copy (String)


1. 지정된 String과 동일한 값을 갖는 String의 새 인스턴스를 만듭니다.

<구문>

public static string Copy(
	string str
)

<매개 변수>

str : 복사할 문자열입니다.

<반환 값>

str과 동일한 값을 갖는 새 문자열입니다.

<설명>

1. Copy 메서드가 반환 되는 String 객체를 동일한 값으로 원래 문자열에 있지만 서로 다른 개체 참조를 나타냅니다.

2. 기존 문자열 참조를 추가적인 객체 변수에 할당하는 할당 연산에서 차이가 있습니다.

3. 이 예제에서는 차이점을 보여줍니다(illustrate).

<예제>

1. 다음 예제에서는 값이 서로 다른 두 string 개체를 만듭니다.

2. 첫번째 값을 두번째 문자열에 할당하는 Copy 메서드를 호출할 때 출력(output)은 문자열의 값이 현재 동일하더라도 다른 객체 참조한다는 것을 나타냅니다.

3. 반면에(On the other hand) 첫 번째 문자열이 두번째 문자열에 할당될 때 동일한 객체 참조를 가지기 때문에 두 쿤자열은 동일한 값을 가집니다.


using System;

class Example
{
   public static void Main() 
   {
      string str1 = "abc";
      string str2 = "xyz";

      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);

      Console.WriteLine("\nAfter String.Copy...");
      str2 = String.Copy(str1);
      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
      Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1, str2));
      Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));

      Console.WriteLine("\nAfter Assignment...");
      str2 = str1;
      Console.WriteLine("str1 = '{0}'", str1);
      Console.WriteLine("str2 = '{0}'", str2);
      Console.WriteLine("ReferenceEquals: {0}", Object.ReferenceEquals(str1, str2));
      Console.WriteLine("Equals: {0}", Object.Equals(str1, str2));
   }
}
// The example displays the following output:
//       str1 = 'abc'
//       str2 = 'xyz'
//       
//       After String.Copy...
//       str1 = 'abc'
//       str2 = 'abc'
//       ReferenceEquals: False
//       Equals: True
//       
//       After Assignment...
//       str1 = 'abc'
//       str2 = 'abc'
//       ReferenceEquals: True
//       Equals: True





String.CopyTo (Int32, Char[], Int32, Int32)


1. 이 인스턴스의 지정한 위치에 있는 지정한 수의 문자(a specified number of characters)를 유니코드 문자 배열의 특정 위치(a specified position)에 복사합니다.

<구문>

public void CopyTo(
	int sourceIndex,
	char[] destination,
	int destinationIndex,
	int count
)

<매개 변수>

sourceIndex : 이 인스턴스에서 복사할 첫 번째 문자의 인덱스

destination : 이 인스턴스의 문자가 복사되는 유니코드 문자의 배열

destinationIndex : destination에서 복사 작업이 시작되는 인덱스

count : 이 인스턴스에서 destination에 복사할 문자의 수

<설명>

1. 이 메서드는 이 인스턴스의 sourceIndex 위치에서 count 문자를 destination character 배열의 destinationIndex 위치에 복사합니다.

2. 이 메서드는 destination 문자 배열을 리사이즈하지 않기 때문에 복사되는 문자를 수용할 충분한 요소의 수를 가져야 합니다. 그렇지 않으면 ArgumentOutOfRangeException을 throw 합니다.

3. sourceIndex 및 destination 는 0부터 시작합니다(zero-based).

<예제>

1. 다음 예제는 CopyTo 메서드를 보여 줍니다.

using System;

public class CopyToTest {
    public static void Main() {

        // Embed an array of characters in a string
        string strSource = "changed";
    char [] destination = { 'T', 'h', 'e', ' ', 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ',
                'a', 'r', 'r', 'a', 'y' };

        // Print the char array
        Console.WriteLine( destination );

        // Embed the source string in the destination string
        strSource.CopyTo ( 0, destination, 4, strSource.Length );

        // Print the resulting array
        Console.WriteLine( destination );

        strSource = "A different string";

        // Embed only a section of the source string in the destination
        strSource.CopyTo ( 2, destination, 3, 9 );

        // Print the resulting array
        Console.WriteLine( destination );
    }
}
// The example displays the following output:
//       The initial array
//       The changed array
//       Thedifferentarray





String.EndsWith (String)


1. 이 문자열 인스턴스의 끝 부분과 지정한 문자열이 일치하는지를 확인합니다.

<구문>

public bool EndsWith(
	string value
)

<매개 변수>

value : 이 인스턴스의 끝 부분에 있는 부분 문자열과 비교할 문자열입니다.

<반환 값>

이 인스턴스의 끝이 true와 일치하면 value이고 그렇지 않으면 false입니다.

<설명>

1. 이 메서드는 value와 같은 길이인 이 인스턴스의 끝에 있는 부분 문자열과 비교해서 같은지를 나타내는 값을 반환합니다.

2. 같으려면, value는 이 동일한 인스턴스의 참조이거나, 이 인스턴스의 끝과 일치해야 합니다.

3. 이 메서드는 현재 문화권 사용해서 단어(대/소문자 구분과 문화권 구분) 비교를 수행합니다.

<호출자 참고 사항>

1. Best Practices for Using Strings in the .NET Framework에서 설명한대로, 기본값을 대체하는 문자열 비교 메서드 호출을 피하고, 대신 매개 변수가 명시적으로 지정되는 메서드를 호출하는 것을 권장합니다.

2. 문자열이 현재 문화권의 문자열 비교 규칙을 사용해서 특정한 부분 문자열로 끝나는지 확인하려면, comparisonType 매개 변수로 StringComparison.CurrentCulture의 값을 가진 EndsWith(String, StringComparison) 메서드 오버로드를 호출하세요.

<예제>

1. 다음 예제에서는 EndsWith(String) 메서드를 사용해서 라인의 끝에서 HTML 끝 태그를 제거하는 StripEndTags 메서드를 정의합니다.

2. StripEndTags 메서드는 재귀적으로(recursively) 호출되어서 라인의 끝에 있는 여러개의 HTML 끝 태그가 제거되도록 보장합니다.

using System;

public class EndsWithTest {
    public static void Main() {

        // process an input file that contains html tags.
        // this sample checks for multiple tags at the end of the line, rather than simply
        // removing the last one.
        // note: HTML markup tags always end in a greater than symbol (>).

        string [] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
                "<b><i><font color=green>This has multiple tags</font></i></b>",
                "<b>This has <i>embedded</i> tags.</b>",
                "This line simply ends with a greater than symbol, it should not be modified>" };

        Console.WriteLine("The following lists the items before the ends have been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        foreach ( string s in strSource )
            Console.WriteLine( s );

        Console.WriteLine();

        Console.WriteLine("The following lists the items after the ends have been stripped:");
        Console.WriteLine("----------------------------------------------------------------");

        // print out the array of strings
        foreach (var s in strSource)
            Console.WriteLine(StripEndTags(s));
    }

    private static string StripEndTags( string item ) {

        bool found = false;

        // try to find a tag at the end of the line using EndsWith
        if (item.Trim().EndsWith(">")) {

            // now search for the opening tag...
            int lastLocation = item.LastIndexOf( "</" );

            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 ) {
                found = true;
                item =  item.Substring( 0, lastLocation );
            }    
        }

        if (found)
           item = StripEndTags(item);

        return item;
    }
}
// The example displays the following output:
//    The following lists the items before the ends have been stripped:
//    -----------------------------------------------------------------
//    <b>This is bold text</b>
//    <H1>This is large Text</H1>
//    <b><i><font color=green>This has multiple tags</font></i></b>
//    <b>This has <i>embedded</i> tags.</b>
//    This line simply ends with a greater than symbol, it should not be modified>
//    
//    The following lists the items after the ends have been stripped:
//    ----------------------------------------------------------------
//    <b>This is bold text
//    <H1>This is large Text
//    <b><i><font color=green>This has multiple tags
//    <b>This has <i>embedded</i> tags.
//    This line simply ends with a greater than symbol, it should not be modified>





String.Equals (String)


1. 이 인스턴스와 지정한 다른 String 개체의 값이 같은지를 확인합니다(determine).

<구문>

public bool Equals(
	string value
)

<매개 변수>

value : 이 이스턴스와 비교할 문자열

<반환 값>

value 매개 변수의 값이 이 인스턴스의 값과 같으면 true, 그렇지 않으면 false

<구현>

IEquatable<T>.Equals(T)

<설명>

이 메서드는 서수(대/소문자 구분과 문화권 비구분) 비교를 수행합니다.

<예제>

1. 다음 예제는 Equals 메서드를 보여줍니다.

2. 제목형(title-cased) 단어 "Flle"과 동일한 단어를 비교, 동일한 소문자와, 동일한 대문자와 그리고 LATIN SMALL LETTER I (U+0069)가 아니라, LATIN SMALL LETTER DOTLESS I (U+0131)를 포함하는 단어를 비교합니다.

3. Equals(String) 메서드가 서수 비교를 수행하기 때문에, 동일한 단어와의 비교만 true를 반환합니다.

using System;

public class Example
{
   public static void Main()
   {
      Console.OutputEncoding = System.Text.Encoding.UTF8;
      string word = "File";
      string[] others = { word.ToLower(), word, word.ToUpper(), "fıle" };
      foreach (string other in others)
      {
         if (word.Equals(other)) 
            Console.WriteLine("{0} = {1}", word, other);
         else
            Console.WriteLine("{0} {1} {2}", word, '\u2260', other);
      }        
   }
}
// The example displays the following output:
//       File ≠ file
//       File = File
//       File ≠ FILE
//       File ≠ fıle



 


 

String.GetEnumerator ()

 

1. 이 문자열의 개별 문자에서 반복(iterate)될 수 있는 개체를 검색합니다(retrieve).

<구문>

public CharEnumerator GetEnumerator()
<반환 값>

Type : System.CharEnumerator

열거자 개체(enumerator object)

<설명>

  

 T:System.CharEnumerator 객체를 검색해서 문자열을 열거하는 System.String.GetEnumerator 메서드를 호출이 아니라 대신에 사용 언어(C#, C++/CLR, Visual Basic)의 반복 구성을 사용하세요.

1. 이 메서드로 문자열의 개별 문자를 반복할 수 있습니다.

2. Visual Basic For Eachand, C# foreach 문이 이 메서드를 호출합니다.

3. 문자열 인스턴스의 문자들에 읽기 전용 접근을 제공하는 T:System.CharEnumerator 객체를 반환합니다.

<예제>

1. 다음 예제는 여러개의 문자열의 문자들을 반복하고, 각 개별 문자들에 대한 정보를 표시합니다

2. M:System.String.GetEnumerator 메서드를 호출하기 보다는 언어의 반복 구성을 사용하세요.

using System;

class Example
{
   public static void Main() 
   {
      EnumerateAndDisplay("Test Case");
      EnumerateAndDisplay("This is a sentence.");
      EnumerateAndDisplay("Has\ttwo\ttabs" );
      EnumerateAndDisplay("Two\nnew\nlines");
   }

   static void EnumerateAndDisplay(String phrase)
   {
      Console.WriteLine("The characters in the string \"{0}\" are:",
                        phrase);

      int CharCount = 0;
      int controlChars = 0;
      int alphanumeric = 0;
      int punctuation = 0;

      foreach (var ch in phrase) {
         Console.Write("'{0}' ", ! Char.IsControl(ch) ? ch.ToString() : 
                                     "0x" + Convert.ToUInt16(ch).ToString("X4"));
         if (Char.IsLetterOrDigit(ch)) 
            alphanumeric++;
         else if (Char.IsControl(ch)) 
            controlChars++;
         else if (Char.IsPunctuation(ch)) 
            punctuation++;             
         CharCount++;
      }

      Console.WriteLine("\n   Total characters:        {0,3}", CharCount);
      Console.WriteLine("   Alphanumeric characters: {0,3}", alphanumeric);
      Console.WriteLine("   Punctuation characters:  {0,3}", punctuation);
      Console.WriteLine("   Control Characters:      {0,3}\n", controlChars);
   }
}
// The example displays the following output:
//    The characters in the string "Test Case" are:
//    'T' 'e' 's' 't' ' ' 'C' 'a' 's' 'e'
//       Total characters:          9
//       Alphanumeric characters:   8
//       Punctuation characters:    0
//       Control Characters:        0
//    
//    The characters in the string "This is a sentence." are:
//    'T' 'h' 'i' 's' ' ' 'i' 's' ' ' 'a' ' ' 's' 'e' 'n' 't' 'e' 'n' 'c' 'e' '.'
//       Total characters:         19
//       Alphanumeric characters:  15
//       Punctuation characters:    1
//       Control Characters:        0
//    
//    The characters in the string "Has       two     tabs" are:
//    'H' 'a' 's' '0x0009' 't' 'w' 'o' '0x0009' 't' 'a' 'b' 's'
//       Total characters:         12
//       Alphanumeric characters:  10
//       Punctuation characters:    0
//       Control Characters:        2
//    
//    The characters in the string "Two
//    new
//    lines" are:
//    'T' 'w' 'o' '0x000A' 'n' 'e' 'w' '0x000A' 'l' 'i' 'n' 'e' 's'
//       Total characters:         13
//       Alphanumeric characters:  11
//       Punctuation characters:    0
//       Control Characters:        2





String.GetHashCode ()


1. 해당 문자열에 대한 해시 코드를 반환합니다.

<구문>

public override int GetHashCode()

<반환 값>

부호 있는 32비트 정수 해시 코드입니다.

<설명>

1. M:System.String.GetHashCode의 동작은 CLR의 어느 버전에서 다른 버전으로 변경이 될 수 있는 그 구현에 의존적입니다.

2. 이유는 M:System.String.GetHashCode의 성능(Performance) 향상입니다.

 중요 

 1. 두 문자열 객체가 동일하다면 M:System.String.GetHashCode 메서드는 동일한 값을 반환합니다.

 2. 그러나, 각 고유 문자열 값에 대해서 고유 해시 코드 값이 있는 것은 아닙니다.

 3. 다른 문자열들이 같은 해시 코드를 반환할 수도 있습니다.

 4. 해시 코드가 안정적이라고 보장되지는 않습니다.

 5. 동일한 문자열에 대한 해시 코드는 .NET Framework의 버전과 .NET Framework의 싱글 버전에 대한 플랫폼(32비트와 64비트와 같은)에 따라 다를 수 있습니다.

 6. 몇몇 경우에는 애플리케이션 도메인에 따라서도 다를 수 있습니다.

 7. 그 결과 해시 코드는 만들어진 애플리케이션 도메일의 외부에서, 컬렉션의 키 필드에서, 그리고 지속되어서는 안됩니다.

 8. 마지막으로 암호에 있어서 강력한 해시(cryptographically strong hash)가 필요하다면 암호 해싱 함수에 의해서 반환된 값 대신에 해시 코드를 사용해서는 안됩니다.

 9. 암호화 해시는 T:System.Security.Cryptography.HashAlgorithm 또는 T:System.Security.Cryptography.KeyedHashAlgorithm 클래스에서 파생된 클래스를 사용하세요.

 10. 자세한 내용은 M:System.Object.GetHashCode를 참조하세요.

3. 데스크탑 앱에서 해당 앱 도메인 기반으로 고유 해시 코드를 생성할 수 있습니다.

4. 이것은 충돌의 수를 줄일 수 있고, 해시 테이블을 사용하는 삽입(insertions) 및 검색(lookups)의 전반적인 성능(overall performance)을 향상시킬 수 있습니다.

5. 다음 예제에서는 사용 방법에 대해서 보여줍니다.

6. "This is a string"의 값을 가진 private string constant 를 포함하는 DisplayString 클래스를 정의합니다.

7. 또한 해당 메서드가 실행 중인 앱 도메인의 이름과 함께 문자열의 값과 해시코드를 보여주는 ShowStringHashCode 메서드를 포함합니다.


using System;

public class Example
{
   public static void Main()
   {
      // Show hash code in current domain.
      DisplayString display = new DisplayString();
      display.ShowStringHashCode();

      // Create a new app domain and show string hash code.
      AppDomain domain = AppDomain.CreateDomain("NewDomain");
      var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, 
                                                          "DisplayString");   
      display2.ShowStringHashCode();
   }
}

public class DisplayString : MarshalByRefObject
{
   private String s = "This is a string.";

   public override bool Equals(Object obj)
   {
      String s2 = obj as String; 
      if (s2 == null)
         return false;
      else
         return s == s2; 
   }

   public bool Equals(String str)
   {
      return s == str;
   }    

   public override int GetHashCode()
   {
      return s.GetHashCode();
   }

   public override String ToString() 
   {
      return s;
   }

   public void ShowStringHashCode()
   {
      Console.WriteLine("String '{0}' in domain '{1}': {2:X8}",
                        s, AppDomain.CurrentDomain.FriendlyName, 
                        s.GetHashCode());
   }
}


8. 설정 파일(a configuration file) 없이 example를 실행하면 다음과 비슷한 결과가 출력됩니다.

9. 문자열에 대한 해시 코드는 두 앱 도메인에서 동일합니다.


String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC String 'This is a string.' in domain 'NewDomain': 941BCEAC


10. 그러나 example 디렉토리에 다음의 설정 파일을 추가하고 실행한다면 같은 문자열에 대한 해시 코드는 앱도메인에 따라 달라집니다.


<?xml version ="1.0"?> <configuration> <runtime> <UseRandomizedStringHashAlgorithm enabled="1" /> </runtime> </configuration>


11. 설정 파일이 존재한다면 다음과 같은 결과물을 보여줍니다.


String 'This is a string.' in domain 'PerDomain.exe': 5435776D String 'This is a string.' in domain 'NewDomain': 75CC8236


 중요

 1. 해시 코드는 효율적으로 해시 테이블에 keyed 객체를 삽입하고 검색하는데 사용합니다.

 2. 그러나, 해시 코드가 고유적으로 문자열을 식별하지 못합니다.

 3. 동일한 문자열은 같은 해시 코드를 가지지만, CLR은 또한 다른 문자열에 같은 해시 코드를 할당할 수 있습니다.

 4. 게다가, 해시 코드는 .NET Framework 버전에 따라, 싱글 버전 내의 플랫폼, 앱 도메인에 따라 다를 수 있습니다.

 5. 그렇게 때문에, 해시 코드 값을 직렬화(serialize) 또는 지속(persist)해서는 안됩니다.

 6. 또한, 해시 테이블 또는 딕셔너리에서 키로 사용해서도 안됩니다.


12. 해시 코드와 GetHashCode 메소드의 사용에 대한 자세한 내용은 M:System.Object.GetHashCode를 차조하세요.

<호출자 참고 사항>

1. M:System.String.GetHashCode에 의해 반환되는 값은 플랫폼에 의존적이고 .NET Framework의 32비트와 64비트 버전에 따라 다릅니다. 또한 .NET Framework의 버전에 따라 다를 수 있습니다.

 경고

 1. 해시 코드의 목적은 효율적인 삽입 및 해시 테이블 기반의 컬렉션에서의 검색입니다.

 2. 해시 코드는 영구적인 값이 아닙니다.

 3. 이러한 이유로.

    1) 해시 코드를 직렬화하거나 데이터베이스에 값을 저장하지 마세요.

    2) keyed 컬렉션에서 객체를 검색하기 위해서 해시 코드를 키로 사용하지 마세요.

    3) 암호화 해싱 함수로 반환되는 값 대신에 해시 코드를 사용하지 마세요. 암호화 해시에 대해서는 T:System.Security.Cryptography.HashAlgorithm 또는 T:System.Security.Cryptography.KeyedHashAlgorithm 클래스에서 파생되는 클래스를 사용하세요.

    4) 두 객체가 동일한지 확인하기 위해서 해시 코드의 동일성을 검사하지 마세요.(동일하지 않은 객체가 동일한 해시 코드를 가질 수 있습니다.) 동일성을 확인하려면 M:System.Object.ReferenceEquals(System.Object,System.Object) 또는 M:System.Object.Equals(System.Object) 메서드를 호출하세요.

<예제>

1. 다음 예제에서는 다양한 입력 문자열들로 M:System.String.GetHashCode 메서드를 보여줍니다.

using System;

class GetHashCode 
{
    public static void Main() 
    {
        DisplayHashCode( "" );
        DisplayHashCode( "a" );
        DisplayHashCode( "ab" );
        DisplayHashCode( "abc" );
        DisplayHashCode( "abd" );
        DisplayHashCode( "abe" );
        DisplayHashCode( "abcdef" );
        DisplayHashCode( "abcdeg" );
        DisplayHashCode( "abcdeh" );
        DisplayHashCode( "abcdei" );
        DisplayHashCode( "Abcdeg" );
        DisplayHashCode( "Abcdeh" );
        DisplayHashCode( "Abcdei" );
    }

    static void DisplayHashCode( String Operand )
    {
        int     HashCode = Operand.GetHashCode( );
        Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}",
                          Operand, HashCode );
    }
}
/*
      This example displays output like the following:
      The hash code for "" is: 0x2D2816FE, 757602046
      The hash code for "a" is: 0xCDCAB7BF, -842352705
      The hash code for "ab" is: 0xCDE8B7BF, -840386625
      The hash code for "abc" is: 0x2001D81A, 536991770
      The hash code for "abd" is: 0xC2A94CB5, -1029092171
      The hash code for "abe" is: 0x6550C150, 1699791184
      The hash code for "abcdef" is: 0x1762906D, 392335469
      The hash code for "abcdeg" is: 0x1763906D, 392401005
      The hash code for "abcdeh" is: 0x175C906D, 391942253
      The hash code for "abcdei" is: 0x175D906D, 392007789
      The hash code for "Abcdeg" is: 0x1763954D, 392402253
      The hash code for "Abcdeh" is: 0x175C954D, 391943501
      The hash code for "Abcdei" is: 0x175D954D, 392009037
*/





Object.GetType 메서드


1. 현재 인스턴스의 Type을 가져옵니다.

<구문>

public Type GetType()

<반환 값>

1. 현재 인스턴스의 정확한(exact) 런타임 형식입니다.

<설명>

1. 동일한 런타임 형식을 가지는 두 객체 x와 y에 대해서 Object.ReferenceEquals(x.GetType(), y.GetType())은 true를 반환합니다.

2. 다음 예제에서는 ReferenceEquals 메서드와 함께 GetType 메서드를 사용해서 하나의 숫자 값이 두 개의 다른 숫자 값과 같은 형식인지 확인합니다.

int n1 = 12;
int n2 = 82;
long n3 = 12;

Console.WriteLine("n1 and n2 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n2.GetType()));
Console.WriteLine("n1 and n3 are the same type: {0}",
                  Object.ReferenceEquals(n1.GetType(), n3.GetType()));
// The example displays the following output:
//       n1 and n2 are the same type: True
//       n1 and n3 are the same type: False
System_CAPS_note참고

개체가 특정 형식 인지를 확인 하려면 해당 언어의 형식 비교 키워드 또는 구성을 사용할 수 있습니다. 예를 들어 비주얼 베이직에서는 TypeOf…Is 구성 또는 C#에서는 is 키워드입니다.

3. Type 객체는 현재 Object의 클래스와 연결된 메타데이터를 노출합니다.

<예제>

1. 다음 코드 예제에서는 GetType 현재 인스턴스의 런타임 형식을 반환합니다.

using System;

public class MyBaseClass {
}

public class MyDerivedClass: MyBaseClass {
}

public class Test 
{
   public static void Main() 
   {
      MyBaseClass myBase = new MyBaseClass();
      MyDerivedClass myDerived = new MyDerivedClass();
      object o = myDerived;
      MyBaseClass b = myDerived;

      Console.WriteLine("mybase: Type is {0}", myBase.GetType());
      Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
      Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
      Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
   }
}
// The example displays the following output:
//    mybase: Type is MyBaseClass
//    myDerived: Type is MyDerivedClass
//    object o = myDerived: Type is MyDerivedClass
//    MyBaseClass b = myDerived: Type is MyDerivedClass





String.IndexOf (Char)


1. 이 문자열에서 맨 처음 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스를 반환합니다.

<구문>

public int IndexOf(
	char value
)

<매개 변수>

value : 검색할(seek) 유니코드 문자입니다.

<반환 값>

해당 문자가 있으면 value의 인덱스 위치(0부터 시작)이고, 그렇지 않으면 -1입니다.

<설명>

1. 인덱스 번호는 0부터 시작합니다.

2. 이 메서드는 유니코드 스칼라 값이 같은 서수(문화권 비구분) 검색을 수행합니다.

3. 문화권 구분 검색을 수행하려면 CompareInfo.IndexOf 메서드를 사용합니다.

4. 합자(ligature) "Æ" (U+00C6)와 같이 미리 구성된(precomposed) 문자를 나타내는(represent) 유니코드 스칼라 값이 문화권에 따라 "AE" (U+0041, U+0045) 와 같은 올바른 순서로 문자의 구성요소가 일치한다면 동일하다고 간주될 수 있습니다.

<예제>

1. 다음 예제에서는 IndexOf 메서드를 사용해서 문자열에서 문자를 검색하는 방법을 보여줍니다.

using System;

class Example
{
   static void Main()
   {
      // Create a Unicode string with 5 Greek Alpha characters.
      String szGreekAlpha = new String('\u0391',5);

      // Create a Unicode string with 3 Greek Omega characters.
      String szGreekOmega = "\u03A9\u03A9\u03A9";

      String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, 
                                            szGreekOmega.Clone());

      // Display the entire string.
      Console.WriteLine("The string: {0}", szGreekLetters);

      // The first index of Alpha.
      int ialpha = szGreekLetters.IndexOf('\u0391');
      // The first index of Omega.
      int iomega = szGreekLetters.IndexOf('\u03A9');

      Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                        ialpha);
      Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                        iomega);
   }
} 
// The example displays the following output:
//    The string: OOO?????OOO
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0





String.IndexOfAny 메서드 (Char[])


1. 유니코드 문자의 지정된 배열에서 있는 문자 중에서 이 인스턴스에서 맨 처음 발견되는 문자의 0부터 시작하는 인덱스를 보고합니다.

<구문>

public int IndexOfAny(
	char[] anyOf
)

<매개 변수>

anyOf : 검색할(seek) 문자를 하나 이상 포함하는 유니코드 문자 배열입니다.

<반환 값>

1. 이 인스턴스에서 anyOf의 문자가 처음 발견된 인덱스 위치(0부터 시작)입니다.

2. anyOf의 문자가 발견되지 않으면 -1입니다.

<설명>

1. anyOf 검색은 대/소문자를 구분합니다.

<예제>

1. 다음 예제에서는 IndexOfAny 메서드를 사용하여 사용자가 입력한 문자열에 잘못된 문자가 있는지 확인합니다.

/* Get the tree node under the mouse pointer and 
   save it in the mySelectedNode variable. */
private void treeView1_MouseDown(object sender, 
  System.Windows.Forms.MouseEventArgs e)
{
   mySelectedNode = treeView1.GetNodeAt(e.X, e.Y);
}

private void menuItem1_Click(object sender, System.EventArgs e)
{
   if (mySelectedNode != null && mySelectedNode.Parent != null)
   {
      treeView1.SelectedNode = mySelectedNode;
      treeView1.LabelEdit = true;
      if(!mySelectedNode.IsEditing)
      {
         mySelectedNode.BeginEdit();
      }
   }
   else
   {
      MessageBox.Show("No tree node selected or selected node is a root node.\n" + 
         "Editing of root nodes is not allowed.", "Invalid selection");
   }
}

private void treeView1_AfterLabelEdit(object sender, 
         System.Windows.Forms.NodeLabelEditEventArgs e)
{
   if (e.Label != null)
   {
     if(e.Label.Length > 0)
     {
        if (e.Label.IndexOfAny(new char[]{'@', '.', ',', '!'}) == -1)
        {
           // Stop editing without canceling the label change.
           e.Node.EndEdit(false);
        }
        else
        {
           /* Cancel the label edit action, inform the user, and 
              place the node in edit mode again. */
           e.CancelEdit = true;
           MessageBox.Show("Invalid tree node label.\n" + 
              "The invalid characters are: '@','.', ',', '!'", 
              "Node Label Edit");
           e.Node.BeginEdit();
        }
     }
     else
     {
        /* Cancel the label edit action, inform the user, and 
           place the node in edit mode again. */
        e.CancelEdit = true;
        MessageBox.Show("Invalid tree node label.\nThe label cannot be blank", 
           "Node Label Edit");
        e.Node.BeginEdit();
     }
   }
}




String.Insert 메서드 (Int32, String)


1. 이 인스턴스의 지정된 인덱스 위치에 지정된 문자열이 삽입되는 새로운 문자열을 반환합니다.

<구문>

public string Insert(
	int startIndex,
	string value
)

<매개 변수>

startIndex : 삽입되는 0부터 시작하는 인덱스 위치

value : 삽입할 문자열

<반환 값>

1. 이 인스턴스와 동일한 새로운 문자열이지만 value가 startIndex 위치에 삽입된다.

<설명>

1. startIndex가 이 인스턴스의 길이와 같다면 value는 이 인스턴스의 끝에 붙는다(append).

System_CAPS_note참고

1. 이 메서드는 현재 인스턴스의 값을 수정하지 않습니다.

2. 대신에, 현재 인스턴스에 value가 삽입되는 새로운 문자열을 반환합니다.

2. 예를 들어, "abc".Insert(2, "XYZ")의 반환 값은 "abXYZc")입니다.

<예제>

1. 다음 콘솔 프로그램은 M:System.String.Insert(System.Int32, System.String) 메서드의 간단한 데모를 제공합니다.

using System;

public class Example {
    public static void Main() 
    {
        string animal1 = "fox";
        string animal2 = "dog";

        string strTarget = String.Format("The {0} jumped over the {1}.", 
                                         animal1, animal2);

        Console.WriteLine("The original string is:{0}{1}{0}", 
                          Environment.NewLine, strTarget);

        Console.Write("Enter an adjective (or group of adjectives) " +
                      "to describe the {0}: ==> ", animal1);
        string adj1 = Console.ReadLine();

        Console.Write("Enter an adjective (or group of adjectives) " + 
                      "to describe the {0}: ==> ", animal2);    
        string adj2 = Console.ReadLine();

        adj1 = adj1.Trim() + " ";
        adj2 = adj2.Trim() + " ";

        strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
        strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);

        Console.WriteLine("{0}The final string is:{0}{1}", 
                          Environment.NewLine, strTarget);
    }
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumped over the dog.
//       
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//       
//       The final string is:
//       The bold fox jumped over the lazy dog.





String.Join 메서드 (String, String[], Int32, Int32)


1. 각 요소 사이에 지정된 구분 기호를 사용하여 각 요소 문자열 배열의 지정된 요소를 연결합니다.

<구문>

public static string Join(
	string separator,
	string[] value,
	int startIndex,
	int count
)

<매개 변수>

separator : 구분 기호로 사용할 문자열입니다. value에 둘 이상의 요소가 있는 경우에만 구분 기호가 반환된 문자열에 포함됩니다.

value : 연결할 요소를 포함하는 배열입니다.

startIndex : 사용할 value의 첫 번째 요소입니다.

count : value 중에서 사용할 요소의 수입니다.

<반환 값>

1. 구분 기호로 분리된 value의 문자열로 구성되는 문자열입니다.

2. count가 0이라면 또는 value에 요소가 없다면 또는 separator와 value의 모든 요소가 String.Empty

<설명>

1. 예를 들어, 구분 기호가 ", " 이고, value의 요소가 "apple", "orange", "grape", "pear" 이라면, Join(separator, value, 1, 2)는 "orange, grape"를 반환합니다.

2. 구분 기호가 null이면 빈 문자열(String.Empty)가 대신 사용됩니다.

3. value에 어떤 요소에도 null이 있다면, 빈 문자열이 대신 사용됩니다.

<예제>

다음 예제에서는 과일 이름의 배열에서 두 요소를 연결합니다(concatenate).

// Sample for String.Join(String, String[], int int)
using System;

class Sample {
    public static void Main() {
    String[] val = {"apple", "orange", "grape", "pear"};
    String sep   = ", ";
    String result;

    Console.WriteLine("sep = '{0}'", sep);
    Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
    result = String.Join(sep, val, 1, 2);
    Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
    }
}
/*
This example produces the following results:
sep = ', '
val[] = {'apple' 'orange' 'grape' 'pear'}
String.Join(sep, val, 1, 2) = 'orange, grape'
*/





String.LastIndexOf 메서드 (Char)


1. 이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다.

<구문>

public int LastIndexOf(
	char value
)

<매개 변수>

value : 검색할 유니코드 문자입니다.

<반환 값>

1. 해당 문자가 있으면 value의 0부터 시작하는 인덱스 위치입니다.

2. 해당 문자가 없으면 -1을 반환합니다.

<설명>

1. 인덱스 번호는 0부터 시작합니다.

2. 즉, 문자열의 첫 번째 문자는 인덱스 0이며 마지막은 Length -1입니다.

3. 이 메서드는 이 인스턴스의 마지막 문자 위치에서 검색을 시작하고 뒤에서 앞으로 진행합니다(proceed backward toward the beginning).

4. value가 발견되거나 첫 문자 위치가 검사된 후 끝납니다.

5. 검색은 대/소문자를 구분합니다.

<예제>

1. 다음 예제에서는 ExtractFilename 메서드를 정의합니다.

2. LastIndexOf(Char) 메서드를 사용하여 문자열에서 마지막 디렉토리 구분 기호 문자를 찾아서 문자열의 파일 이름을 추출(extract)합니다.

using System;
using System.IO;

public class TestLastIndexOf
{
   public static void Main()
   {
      string filename;

      filename = ExtractFilename(@"C:\temp\");
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);

      filename = ExtractFilename(@"C:\temp\delegate.txt"); 
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);

      filename = ExtractFilename("delegate.txt");      
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);

      filename = ExtractFilename(@"C:\temp\notafile.txt");
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
   }

   public static string ExtractFilename(string filepath)
   {
      // If path ends with a "\", it's a path only so return String.Empty.
      if (filepath.Trim().EndsWith(@"\"))
         return String.Empty;

      // Determine where last backslash is.
      int position = filepath.LastIndexOf('\\');
      // If there is no backslash, assume that this is a filename.
      if (position == -1)
      {
         // Determine whether file exists in the current directory.
         if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath)) 
            return filepath;
         else
            return String.Empty;
      }
      else
      {
         // Determine whether file exists using filepath.
         if (File.Exists(filepath))
            // Return filename without file path.
            return filepath.Substring(position + 1);
         else
            return String.Empty;
      }
   }
}





String.PadLeft 메서드 (Int32)


1. 지정한 길이만큼 왼쪽의 안쪽 여백을 공백으로 채워서 이 인스턴스의 문자를 오른쪽에 맞추는 새 문자열을 반환합니다.

<구문>

public string PadLeft(
	int totalWidth
)

<매개 변수>

totalWidth : 결과 문자열에 있는 문자 수는 원래 문자 수와 추가 안족  여백 문자 수를 합한 값과 같습니다.

<반환 값>

결과 문자열에 있는 문자 수는 원래 문자의 수와 추가 안쪽 여백 수를 합한 값과 같습니다.

<반환 값>

1. 이 인스턴스와 동일하지만 오른쪽으로 맞춰지고 안쪽 여백이 totalWidth의 길이만큼 공백 문자로 채워진 새 문자열입니다.

2. 그러나 totalWidth가 이 인스턴스의 길이보다 작을 경우 메서드는 기존 인스턴스에 대한 참조를 반환합니다.

3. totalWidth가 이 인스턴스의 길이와 같을 경우 메서드는 이 인스턴스와 동일한 새 문자열을 반환합니다.

<설명>

1. 유니코드 공백은 16진수 0x0020으로 정의됩니다.

2. PadLeft(Int32) 메서드는 반환된 문자열의 시작 부분을 채웁니다.

3. 즉, 오른쪽에서 왼쪽 언어를 사용할 때 문자열의 오른쪽 부분을 채웁니다.

System_CAPS_note참고

1. PadLeft 메서드가 현재 인스턴스를 공백 문자로 채우는 경우, 이 메서드는 현재 인스턴스의 값을 수정하지 않습니다.

2. 대신, 총 길이가 totalWidth 문자가 되도록 앞에 공백을 채워서 새로운 문자열을 반환합니다.

<예제>

string str = "BBQ and Slaw";
Console.WriteLine(str.PadLeft(15));  // Displays "   BBQ and Slaw".
Console.WriteLine(str.PadLeft(5));   // Displays "BBQ and Slaw".






'프로그래밍 > C#' 카테고리의 다른 글

대리자 Action, Func  (0) 2016.07.08
String.Format 메서드  (0) 2016.06.28
Windows Forms 컨트롤의 다중 스레딩  (0) 2016.06.21
스레드  (0) 2016.06.14
보간된 문자열(Interpolated strings)  (0) 2016.06.14
:
Posted by 지훈2