如何访问字符串数组元素进行搜索?

时间:2019-03-03 22:01:15

标签: c#

我有一个包含数字的文本文件,并将其保存在字符串数组中。 我的文本文件的一行是这样的: 2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 85 90 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21 < / p>

每行保存在字符串数组的索引之一中。 现在我该如何以int类型访问数组元素并搜索和计算所有数组? 这是我的数组:

string [] lines = File.ReadAllLines(txtPath.Text);

例如,我想返回所有数组中包含数字'14'的数组索引。

4 个答案:

答案 0 :(得分:0)

首先,您必须以字符串数组格式获取文件的所有内容:

public string[] readAllInFile(string filepath){
            var lines = File.ReadAllLines(path);
            var fileContent = string.Join(' ',lines);//join all lines of file content in one variable
            return fileContent.Split(' ');//each word(in your case each number) in one index of array
        }

在使用时间中,您可以这样做:

var MyFileContent = readAllInFile(txtPath.Text);
int x= Convert.ToInt32(MyFileContent[2]);
IEnumerable<int> numbers = MyFileContent.Select(m=> int.Parse(m);)
var sumeOf = numbers.sum();

您可以使用linq在集合上使用更多工具。

答案 1 :(得分:0)

var linesAsInts = lines.Select(x => x.Split(' ').Select(int.Parse));

var filteredLines = linesAsInts.Where(x => x.Contains(14));

答案 2 :(得分:0)

// define value delimiters.
var splitChars = new char[] { ' ', ':' };

// read lines and parse into enumerable of enumerable of ints.
var lines = File.ReadAllLines(txtPath.Text)
    .Select(x => x.Split(splitChars)
        .Select(int.Parse));

// search in array.
var occurences = lines
    .Select((line,lineIndex) => line
        .Select((integer, integerIndex) => new { integer, integerIndex })
        .Where(x => x.integer == 10)
        .Select(x => x.integerIndex));

// calculate all of array.
var total = lines.Sum(line => line.Sum());

答案 3 :(得分:0)

这是解决问题的最简单,最清晰的方法。我评论了一下,以便您可以更好地了解整个程序中发生了什么。

class Program
  {
    static void Main(string[] args)
    {
      // this is your array of strings (lines)
      string[] lines = new string[1] {
        "2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
      };

      // this dictionary contains the line index and the list of indexes containing number 14
      // in that line
      Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();

      // iterating over lines array
      for (int i = 0; i < lines.Length; i++)
      {
        // creating the list of indexes and the dictionary key
        List<int> indexes = new List<int>();
        dict.Add(i, indexes);
        // splitting the line by space to get numbers
        string[] lineElements = lines[i].Split(' ');
        // iterating over line elements
        for (int j = 0; j < lineElements.Length; j++)
        {
          int integerNumber;
          // checking if the string lineElements[j] is a number (because there also this case 114:275:5)
          if (int.TryParse(lineElements[j], out integerNumber))
          {
            // if it is we check if the number is 14, in that case we add that index to the indexes list
            if (integerNumber == 14)
            {
              indexes.Add(j);
            }
          }
        }
      }

      // Printing out lines and indexes:
      foreach (int key in dict.Keys)
      {
        Console.WriteLine(string.Format("LINE KEY: {0}", key));
        foreach (int index in dict[key])
        {
          Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
        }
        Console.WriteLine("------------------");
      }

      Console.ReadLine();
    }
  }

更新1:

根据您的要求:

  

特别感谢您的明确回答。如果我想搜索所有数组元素,我该怎么办?这意味着不仅   数字'14'我想打印出现在所有数字的索引   索引

如果要打印所有索引,应Console.WriteLine(j),即内部for周期的索引,而不是检查数字值if (integerNumber == 14)

所以,这是程序:

class Program
  {
    static void Main(string[] args)
    {
      // this is your array of strings (lines)
      string[] lines = new string[1] {
        "2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
      };

      // this dictionary contains the line index and the list of indexes containing number 14
      // in that line
      Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();

      // iterating over lines array
      for (int i = 0; i < lines.Length; i++)
      {
        // creating the list of indexes and the dictionary key
        List<int> indexes = new List<int>();
        dict.Add(i, indexes);
        // splitting the line by space to get numbers
        string[] lineElements = lines[i].Split(' ');
        // iterating over line elements
        for (int j = 0; j < lineElements.Length; j++)
        {
          // printing all indexes of the current line
          Console.WriteLine(string.Format("Element index: {0}", j));
        }
      }

      Console.ReadLine();
    }
  }

更新2:

根据您的要求:

  

如果我要搜索直到第一行“:”的行,然后搜索下一行,我该怎么办?

在使用for的元素上时,您需要打破:周期

class Program
  {
    static void Main(string[] args)
    {
      // this is your array of strings (lines)
      string[] lines = new string[1] {
        "2 3 9 14 23 26 34 36 39 40 52 55 59 63 67 76 85 86 90 93 99 108 114:275:5 8 1 14 10 6 10 18 12 25 7 40 1 30 18 8 2 1 5 21 10 2 21"
      };

      // this dictionary contains the line index and the list of indexes containing number 14
      // in that line
      Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();

      // iterating over lines array
      for (int i = 0; i < lines.Length; i++)
      {
        // creating the list of indexes and the dictionary key
        List<int> indexes = new List<int>();
        dict.Add(i, indexes);
        // splitting the line by space to get numbers
        string[] lineElements = lines[i].Split(' ');
        // iterating over line elements
        for (int j = 0; j < lineElements.Length; j++)
        {
          // I'm saving the content of lineElements[j] as a string
          string element = lineElements[j];
          // I'm checking if the element saved as string contains the string ":"
          if (element.Contains(":"))
          {
            // If it does, I'm breaking the cycle, and I'll continue with the next line
            break;
          }
          int integerNumber;
          // checking if the string lineElements[j] is a number (because there also this case 114:275:5)
          if (int.TryParse(lineElements[j], out integerNumber))
          {
            // if it is we check if the number is 14, in that case we add that index to the indexes list
            if (integerNumber == 14)
            {
              indexes.Add(j);
            }
          }
        }
      }

      // Printing out lines and indexes:
      foreach (int key in dict.Keys)
      {
        Console.WriteLine(string.Format("LINE KEY: {0}", key));
        foreach (int index in dict[key])
        {
          Console.WriteLine(string.Format("INDEX ELEMENT: {0}", index));
        }
        Console.WriteLine("------------------");
      }

      Console.ReadLine();
    }
  }

如您所见,如果您运行这段代码并将其与第一个版本进行比较,则在输出中您将仅获得第一次出现的14的索引,因为第二个出现在字符串之后与: