找到搜索查询之前的计数
Count number before search query is found
我正在尝试确定我必须在 pi 中走多远才能找到用户输入的搜索查询。我尝试使用 system.length
的各种属性,但我无法得到我想要的。我本质上希望能够输入一组数字,并让控制台 return 查询找到了 pi 中的多少个数字。分隔符是 PiClass.CalculatePi
只是为了确保它不会永远 运行。
Console.WriteLine("type string to search");
string searchForThis = Console.ReadLine();
var PiClass = new PiClass();
double.TryParse(PiClass.CalculatePi(3), out double pi);
string piString = pi.ToString();
if (piString.Contains(searchForThis) == true)
{
Console.WriteLine("Located");
}
else
{
Console.WriteLine("Please expend search");
}
Console.Read();
给你:
Console.WriteLine("type string to search");
string searchForThis = Console.ReadLine();
var PiClass = new PiClass();
double.TryParse(PiClass.CalculatePi(3), out double pi);
string piString = pi.ToString();
int location = piString.IndexOf(searchForThis);
if (location >=0)
{
Console.WriteLine("Located at index: " + location.ToString());
}
else
{
Console.WriteLine("Please expend search");
}
Console.Read();
正如我在评论中提到的,您可以使用 string.IndexOf
:
string piString = pi.ToString();
int index = piString.IndexOf(searchForThis);
if (index != -1) {
// There is a subsrting you are looking for.
}
而index
表示搜索字符串之前的字符数。
我正在尝试确定我必须在 pi 中走多远才能找到用户输入的搜索查询。我尝试使用 system.length
的各种属性,但我无法得到我想要的。我本质上希望能够输入一组数字,并让控制台 return 查询找到了 pi 中的多少个数字。分隔符是 PiClass.CalculatePi
只是为了确保它不会永远 运行。
Console.WriteLine("type string to search");
string searchForThis = Console.ReadLine();
var PiClass = new PiClass();
double.TryParse(PiClass.CalculatePi(3), out double pi);
string piString = pi.ToString();
if (piString.Contains(searchForThis) == true)
{
Console.WriteLine("Located");
}
else
{
Console.WriteLine("Please expend search");
}
Console.Read();
给你:
Console.WriteLine("type string to search");
string searchForThis = Console.ReadLine();
var PiClass = new PiClass();
double.TryParse(PiClass.CalculatePi(3), out double pi);
string piString = pi.ToString();
int location = piString.IndexOf(searchForThis);
if (location >=0)
{
Console.WriteLine("Located at index: " + location.ToString());
}
else
{
Console.WriteLine("Please expend search");
}
Console.Read();
正如我在评论中提到的,您可以使用 string.IndexOf
:
string piString = pi.ToString();
int index = piString.IndexOf(searchForThis);
if (index != -1) {
// There is a subsrting you are looking for.
}
而index
表示搜索字符串之前的字符数。