我怎样从c#中读取整个数组 [英] How do I read from the entire array in c#

查看:114
本文介绍了我怎样从c#中读取整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有这个代码,我正在尝试读取数组的索引,我需要它来读取所有不一次只有一个



这是可能的?



I have this code here and I am trying to read the indexes of the array I need it to read all not just one at a time

Is this possible?

string s = textBox1.Text;

           string[] arr = new string[]
   {
       "cat",
       "dog",
       "panther",
       "tiger"
   };

          if (s.Contains(arr[0]))
           {
string v = s.Replace(arr[0], "*********");
              //show message with work that isnt allowed
              MessageBox.Show("Can not use the word " + arr[0]);
               textBox2.Text = v;
           }
           else
           {
               textBox2.Text = s;
           }

推荐答案

我会这样做。

string st = "Bob had a cat and a tiger";
           string[] arr = {
               "cat",
               "dog",
               "panther",
               "tiger"
           };
           foreach (var name in arr)
           {
               if (st.Contains(name))
               {
                   st = st.Replace(name, "****");
                   Console.WriteLine("Cannot use the word " + name);
               }

           }

           Console.WriteLine(st);//Bob had a **** and a ****

           //using linq
           st = "Bob had a dog and a panther";

               foreach (var name in arr.Where(name => st.Contains(name)))
               {
                   st = st.Replace(name, "****");
                   Console.WriteLine("Cannot use the word " + name);
               }
               Console.WriteLine(st);

            //using a StringBuilder with no 'where' clause
           st = "Bob had a dog and a panther";
           StringBuilder msb=new StringBuilder(st);

               foreach (var name in arr)
               {
                   msb.Replace(name, "****");
                   Console.WriteLine("Cannot use the word " + name);
               }
               Console.WriteLine(msb);


使用for循环阅读



use a for loop to read

for(int i = 0; i < arr.Length; i++){
 // arr[ i ]  do something here
}


数组和许多其他集合实现了一个迭代器接口,可以帮助遍历集合(或数组)。

以下是迭代这些数组的一些示例 -

Iterators(C#和Visual Basic) [ ^ ]

如何:遍历数组 [ ^ ]
Arrays and many other collections implement an iterator interface that can help loop through the collection (or array).
Here are some examples of iterating through these arrays -
Iterators (C# and Visual Basic)[^]
How to: Iterate through an array[^]


这篇关于我怎样从c#中读取整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆