StringCollection은 문자열 컬렉션을 다루는 클래스로, System.Collections.Specialized 네임스페이스에 포함되어 있습니다. 이 컬렉션에서는 인덱서(indexer)를 사용하여 지정된 인덱스 위치의 요소를 자유롭게 가져오거나 새로운 값으로 설정할 수 있습니다.
예제 1 – 인덱스로 요소 가져오기
다음은 StringCollection에서 지정된 인덱스의 요소를 가져오는 코드입니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr) {
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Element at 5th index = " + strCol[5]);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
StringCollection elements... A B C D E F G H Element at 5th index = F
strCol[5]처럼 인덱서를 사용하면 5번째 인덱스에 해당하는 요소를 읽어올 수 있습니다. 인덱스는 0부터 시작하므로 5번째 인덱스는 여섯 번째 요소인 "F"가 됩니다.
예제 2 – 인덱스로 요소 설정하기
이번에는 인덱서를 사용해 특정 위치의 값을 변경하는 방법을 살펴보겠습니다.
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
String[] strArr = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
Console.WriteLine("StringCollection elements...");
foreach (string str in strArr) {
Console.WriteLine(str);
}
strCol.AddRange(strArr);
Console.WriteLine("Element at 5th index = " + strCol[5]);
strCol[5] = "M";
Console.WriteLine("Element at 5th index (updated) = " + strCol[5]);
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
StringCollection elements... A B C D E F G H Element at 5th index = F Element at 5th index (updated) = M
strCol[5] = "M"; 구문을 실행하면 5번째 인덱스의 기존 값 "F"가 새로운 값 "M"으로 변경됩니다. 이처럼 StringCollection의 인덱서는 값을 읽고 쓰는 두 가지 용도로 모두 활용할 수 있어, 컬렉션 내 특정 위치의 데이터를 간편하게 관리할 수 있습니다.