Stack.Contains()方法用于检查堆栈中是否存在元素/对象,如果堆栈中存在对象/元素,则返回true,否则返回false。
语法:
bool Stack.Clone(Object);
参数: Object-要检查的对象,是否存在于堆栈中。
返回值: bool –如果堆栈中存在对象,则返回true,否则返回false。
示例
declare and initialize a stack: Stack stk = new Stack(); insertting elements: stk.Push(100); stk.Push(200); stk.Push(300); stk.Push(400); stk.Push(500); checking elements: stk.Contains(100); stk.Contains(800); Output: true false
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
//打印堆栈元素的功能
static void printStack(Stack s)
{
foreach (Object obj in s)
{
Console.Write(obj + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//声明并初始化堆栈
Stack stk = new Stack();
//插入元素
stk.Push(100);
stk.Push(200);
stk.Push(300);
stk.Push(400);
stk.Push(500);
//打印堆栈元素
Console.WriteLine("Stack elements are...");
printStack(stk);
//检查要素
if (stk.Contains(100) == true)
Console.WriteLine("100 exists in the stack");
else
Console.WriteLine("100 does not exist in the stack");
if (stk.Contains(800) == true)
Console.WriteLine("800 exists in the stack");
else
Console.WriteLine("800 does not exist in the stack");
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Stack elements are... 500 400 300 200 100 100 exists in the stack 800 does not exist in the stack
参考:方法Stack.Contains(Object)