Programing

문자열 배열에 값이 포함되어 있는지 확인하고 필요한 경우 위치를 가져옵니다.

lottogame 2020. 6. 12. 22:07
반응형

문자열 배열에 값이 포함되어 있는지 확인하고 필요한 경우 위치를 가져옵니다.


이 문자열 배열이 있습니다.

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

stringArray포함 여부를 결정하고 싶습니다 value. 그렇다면 배열에서 해당 위치를 찾고 싶습니다.

루프를 사용하고 싶지 않습니다. 아무도 내가 어떻게 할 수 있는지 제안 할 수 있습니까?


Array.IndexOf 메서드를 사용할 수 있습니다 .

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    // the array contains the string and the pos variable
    // will have its position in the array
}

var index = Array.FindIndex(stringArray, x => x == value)

우리는 또한 사용할 수 있습니다 Exists:

string[] array = { "cat", "dog", "perl" };

// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));

편집 : 나는 당신도 위치가 필요하다는 것을 알지 못했습니다. IndexOf명시 적으로 구현되었으므로 배열 유형의 값에 직접 사용할 수 없습니다 . 그러나 다음을 사용할 수 있습니다.

IList<string> arrayAsList = (IList<string>) stringArray;
int index = arrayAsList.IndexOf(value);
if (index != -1)
{
    ...
}

(이것은 Array.IndexOfDarin의 답변에 따라 전화하는 것과 유사합니다 -대안 접근법입니다. 왜 명시 적으로 배열 구현 되는지 분명하지 않지만 결코 신경 쓰지 않습니다 ...)IList<T>.IndexOf


사용할 수 있습니다 Array.IndexOf()-요소를 찾을 수 없으며이 경우를 처리 해야하는 경우 -1을 반환합니다.

int index = Array.IndexOf(stringArray, value);

위치를 알고 싶다면 Array.IndexOf () 사용할 수 있습니다.

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

배열에 주어진 값이 포함되어 있는지 확인하는 가장 좋은 System.Collections.Generic.IList<T>.Contains(T item)방법은 다음과 같은 방법 을 사용 하는 것입니다.

((IList<string>)stringArray).Contains(value)

완전한 코드 샘플 :

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");

T[]배열 List<T>은 Count 및 Contains와 같은 몇 가지 메소드를 비공개로 구현합니다 . 명시 적 (비공개) 구현이므로 배열을 먼저 캐스팅하지 않으면 이러한 메소드를 사용할 수 없습니다. 이것은 문자열에서만 작동하지 않습니다.이 클래스를 사용하면 요소의 클래스가 IComparable을 구현하는 한 모든 유형의 배열에 요소가 포함되어 있는지 확인할 수 있습니다.

모든 IList<T>방법이이 방식으로 작동하는 것은 아닙니다. IList<T>배열에서의 Add 메소드 를 사용하려고 하면 실패합니다.


이것을 시도 하고이 요소를 포함하는 색인을 찾고 색인 번호를 int로 설정 한 다음 int가 -1보다 큰지 확인하므로 0 이상이면 다음과 같이 발견됩니다. 인덱스-배열이 0을 기준으로합니다.

string[] Selection = {"First", "Second", "Third", "Fourth"};
string Valid = "Third";    // You can change this to a Console.ReadLine() to 
    //use user input 
int temp = Array.IndexOf(Selection, Valid); // it gets the index of 'Valid', 
                // in our case it's "Third"
            if (temp > -1)
                Console.WriteLine("Valid selection");
            }
            else
            {
                Console.WriteLine("Not a valid selection");
            }

string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};          
string[] fooArray = y.Split(whitespace);  // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };

for (int i = 0; i < target.Length; i++)
{
    string v = target[i];
    string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
    //
    if (results != null)
    { MessageBox.Show(results); }

}

재사용을위한 확장 메소드를 작성했습니다.

   public static bool InArray(this string str, string[] values)
    {
        if (Array.IndexOf(values, str) > -1)
            return true;

        return false;
    }

그것을 부르는 방법 :

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(value.InArray(stringArray))
{
  //do something
}

string[] strArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(Array.contains(strArray , value))
{
    // Do something if the value is available in Array.
}

가장 간단하고 짧은 방법은 다음과 같습니다.

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";

if(stringArray.Contains(value))
{
    // Do something if the value is available in Array.
}

참고 URL : https://stackoverflow.com/questions/7867377/checking-if-a-string-array-contains-a-value-and-if-so-getting-its-position

반응형