Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ค้นหาสตริงในอาร์เรย์สตริง


ภาพรวม

ใช้เมธอด LINQ Contains() เพื่อตรวจสอบว่าสตริงเฉพาะมีอยู่ในอาร์เรย์สตริงหรือไม่ คืนค่า bool

รูปแบบการใช้งาน

string[] arr = { "Bag", "Pen", "Pencil" };
string search = "Pen";
bool found = arr.AsQueryable().Contains(search); // true

ตัวอย่างโค้ดเต็ม

using System;
using System.Linq;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        string[] arr = { "Bag", "Pen", "Pencil" };
        string str = "Pen";
        bool res = arr.AsQueryable().Contains(str);
        Console.WriteLine("String Pen is in the array? " + res);
    }
}

ผลลัพธ์

String Pen is in the array? True

วิธีอื่นๆ

  • Array.Exists(arr, s => s == "Pen") - ไม่ต้องใช้ LINQ
  • arr.Any(s => s == "Pen") - LINQ แบบ predicate
  • Array.IndexOf(arr, "Pen") >= 0 - คืนดัชนี (หรือ -1 หากไม่พบ)
  • สำหรับค้นหาบ่อย ควรใช้ HashSet<string> O(1) แทนอาร์เรย์ O(n)