【发布时间】:2017-05-03 20:16:06
【问题描述】:
所以我有一个文本文件,我想搜索一个数字,如果找到,则输出一个消息号,如果没有,则找不到。
目前我已将文本文件读入一个字符串,并询问用户他们想要搜索的数字。我坚持的部分是线性搜索字符串的代码。我想查找一个字符串,因为我将使用的其他文件可能包含单词。
到目前为止的代码:
public static void search() // Search for values
{
Console.WriteLine("Enter 1 to search through days");
int operation = Convert.ToInt32(Console.ReadLine());
if (operation == 1)
{
String[] myArray = File.ReadAllLines("Data1/Day_1.txt");
Console.WriteLine("Enter number to search");
String myString = Console.ReadLine();
}
}
我看到了一些用于线性搜索的代码,但不确定如何将其正确应用到我的示例中。我了解它是如何工作的,但问题在于以正确的顺序获取代码。不太擅长用c#编码。任何帮助将非常感激。谢谢
通用线性搜索代码:
static int Search(string[] list, string elementSought)
{
bool found = false;
int max = list.Length - 1;
int currentElement = 0;
do
{
if (list[currentElement] == elementSought)
{
found = true;
}
else
{
currentElement = currentElement + 1;
}
} while (!(found == true || currentElement > max));
if (found == true)
{
return currentElement;
}
else
{
return -1;
}
}
更新:
public static void search() // Search for values
{
Console.WriteLine("1=Day 2=Depth");
int operation = Convert.ToInt32(Console.ReadLine());
if (operation == 1)
{
String[] myArray = File.ReadAllLines("Data1/Day_1.txt");
}
else if (operation == 2)
{
String[] myArray = File.ReadAllLines("Data1/Months_1.txt");
}
Console.WriteLine("Enter number to search");
String myString = Console.ReadLine();
int i = 0;
int j = 0;
var regex = new Regex(myString);
foreach (string array in myArray)
{
if (regex.IsMatch(array))
{
i++;
}
else if (regex.IsMatch(array))
{
j++;
}
}
if (i > 0)
{
Console.WriteLine("Found match! - {1} Appeared {0} time(s)",i,myString);
}
else if(j == 0)
{
Console.WriteLine("No Match for {0} in Data", myString);
}
Console.ReadLine();
}
如何更改它,以便如果我选择第二个文件,它会选择它作为我的数组使用的文件?
【问题讨论】:
标签: c# linear-search